C++ - 一个模板类专业函数模板与非类型模板参数
问题描述:
我有一个模板类美孚:C++ - 一个模板类专业函数模板与非类型模板参数
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或类模板
template <class T>
struct validateType : std::false_type {};
template <class A, A val, class B>
struct validateType<Foo<A, val, B>> : std::true_type {};