I have a templated class, for which I want to specialize one of the methods for integral types. I see a lot of examples to do this for templated functions using enable_if trait, but I just can't seem to get the right syntax for doing this on a class method.
What am I doing wrong?
#include <iostream>
using namespace std;
template<typename T>
class Base {
public:
virtual ~Base() {};
void f() {
cout << "base\n";
};
};
template<typename Q>
void Base<std::enable_if<std::is_integral<Q>::value>::type>::f() {
cout << "integral\n";
}
template<typename Q>
void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
cout << "non-integral\n";
}
int main()
{
Base<int> i;
i.f();
Base<std::string> s;
s.f();
return 0;
}
the above code does not compile:
main.cpp:16:60: error: type/value mismatch at argument 1 in template parameter list for ‘template class Base’
16 | void Base<std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^
main.cpp:16:60: note: expected a type, got ‘std::enable_if<(! std::is_integral<_Tp>::value)>::type’
main.cpp:21:61: error: type/value mismatch at argument 1 in template parameter list for ‘template class Base’
21 | void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^
main.cpp:21:61: note: expected a type, got ‘! std::enable_if<(! std::is_integral<_Tp>::value)>::type’
main.cpp:21:6: error: redefinition of ‘template void f()’
21 | void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:16:6: note: ‘template void f()’ previously declared here
16 | void Base<std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~