C++ - 在具有非类型模板参数的模板化 class 上专门化函数模板

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

我有一个 class 模板 Foo:

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

我有一个函数模板 validateType()

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

现在我想将它专门用于某些类型,包括 Foo,以便该函数在编译期间执行一些 static_asserts。我试过这个:

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

还有这个:

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

在第一个中,编译器说:

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() {
                     ^

在第二种情况下我得到

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

应该怎么做?

函数模板不允许部分模板特化。
使用 SFINAE 或 class 模板

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

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

编辑:

Is this supposed to work for template functions as well?

没有。 函数模板不允许部分模板特化。

模板函数,使用SFINAE。

例如,这个示例检查天气T是无符号整数类型(C++17)。

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

但是,对于您的情况,您可以使用 class 模板。使用 class 模板检查 T 是否为模板 class foo 是最简单的方法(顺便说一句,不适用于模板 class foo,std::is_same 是最简单的方法)。