简体   繁体   中英

C++ - specialize function template on a templated class with a non type template parameter

I have a class template Foo:

template <class A, A value, class B>
class Foo {};

And I have a function template validateType()

template <class T>
bool validateType() {
    return false;
}

Now I want to specialize it for some types, including Foo, so that the function performs some static_asserts during compile time. I tried this:

template <class A, class B, Foo<A, A val, B>>
bool validateType() {
    // do some static asserts
}

and this:

template <class A, A val, class B>
bool validateType<Foo<A, val, B>>() {
    // do some static asserts
}

In the first one, the compiler says:

error: wrong number of template arguments (2, should be 3)
 template <class A, class B, Foo<A, A val, B>>
                                            ^~
note: provided for ‘template<class A, A value, class B> class Foo’
 class Foo {};
       ^~~
error: two or more data types in declaration of ‘validateType’
 bool validateType() {
                   ^
error: expected ‘>’ before ‘{’ token
 bool validateType() {
                     ^

And in the second case I get

error: non-class, non-variable partial specialization ‘validateType<Foo<A, val, B> >’ is not allowed
 bool validateType<Foo<A, val, B>>() {
                                   ^

How should this be done?

Partial template specializations are not allowed for function templates.
Use SFINAE or class templates

template <class T>
struct validateType : std::false_type {};

template <class A, A val, class B>
struct validateType<Foo<A, val, B>> : std::true_type {};

Edit:

Is this supposed to work for template functions as well?

NO. Partial template specializations are not allowed for function templates.

for template function, use SFINAE.

For example, this sample check weather T is unsigned integer type(C++17).

template<typename T, std::enable_if_t<std::is_unsigned_v<T>, std::nullptr_t> = nullptr>
T foo(T n);

However, in your case, you chould use class templates. It's simplest way to use class templates to check wether T is template class foo(BTW, not for template class foo, std::is_same is simplest way).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM