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);
std::is_unsigned_v
was added in C++17. before C++17, use std::is_unsigned<T>::value
.std::enable_if_t
was added in C++14. before C++14, use typename std::enable_if<con, T>::type
.std::nullptr_t
can hole only one value(nullptr
) so that I use it for SFINAE enabler.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).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments