Reputation: 2760
I have a class which I need to perform different action based upon the value supplied in the template. But I'm getting an error message "prototype does not match any in class..."
#include <iostream>
#include <type_traits>
using namespace std;
template<int t>
struct A
{
template<typename EqualTwo>
void test();
};
template<int t>
template<typename std::enable_if<t == 2>::value>
void A<t>::test()
{
cout << "T is equal to two.";
}
template<int t>
template<typename std::enable_if<t != 2>::value>
void A<t>::test()
{
cout << "T is not equal to two.";
}
int main() {
A<5> five;
A<2> two;
cout << five.test() << endl;
cout << two.test() << endl;
return 0;
}
Upvotes: 1
Views: 706
Reputation: 42929
Your code is messed up, probably what you want to do is the following:
template<int t, typename Enable = void>
struct A;
template<int t>
struct A<t, typename std::enable_if<t == 2>::type> {
void test() { cout << "T is equal to two." << endl; }
};
template<int t>
struct A<t, typename std::enable_if<t != 2>::type> {
void test() { cout << "T is not equal to two." << endl; }
};
and in main()
:
int main() {
A<5> five;
A<2> two;
five.test();
two.test();
}
Edit:
Unfortunately, you can't specialize a member function of a template class unless you specialize the class itself.
You could however do the following:
template<int t>
struct A {
void test() {
if(t == 2) {
cout << "T is equal to two." << endl;
} else {
cout << "T is not equal to two" << endl;
}
}
};
Upvotes: 2