C ++ - 使用非类型模板参数在模板化类上专门化函数模板

时间:2017-11-25 15:01:35

标签: c++ templates template-specialization specialization

我有一个类模板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>>() {
                                   ^

应该怎么做?

1 个答案:

答案 0 :(得分:1)

功能模板不允许使用部分模板专精 使用SFINAE或类模板

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

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

编辑:

  

这应该适用于模板功能吗?

NO。 功能模板不允许使用部分模板专精。

对于模板功能,请使用SFINAE。

例如,此样本检查天气T是无符号整数类型(C ++ 17)。

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

但是,在您的情况下,您可以使用类模板。使用类模板检查更简单的方法T是模板类foo(BTW,不是模板类foo,std::is_same是最简单的方法)。

相关问题