我有一个类模板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>>() {
^
应该怎么做?
答案 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);
std::is_unsigned_v
已添加到C ++ 17中。在C ++ 17之前,使用std::is_unsigned<T>::value
https://en.cppreference.com/w/cpp/types/is_unsigned std::enable_if_t
已添加到C ++ 14中。在C ++ 14之前,使用typename std::enable_if<con, T>::type
。std::nullptr_t
只能打破一个值(nullptr
),以便我将其用于SFINAE启用程序。但是,在您的情况下,您可以使用类模板。使用类模板检查更简单的方法T是模板类foo(BTW,不是模板类foo,std::is_same
是最简单的方法)。