Reputation: 2441
I've recently discovered template specialization
in C++.
template <typename T>
void fct(void) {}
template <>
void fct<int>(void) {}
int main(void) {
fct<int>();
return 0;
}
I'd like to use template specialization for member functions inside a class.
class MyClass {
public:
template <typename T>
static void fct(void) {}
template <>
static void fct<int>(void) {}
};
int main(void) {
MyClass::fct<int>();
return 0;
}
Unfortunately, compiling with g++
gives me the following error:
error: explicit specialization in non-namespace scope ‘struct MyClass’
error: template-id ‘toto<int>’ in declaration of primary template
I've noticed that doing template specialization works in main scope or in a namespace but not in a struct or in a class.
I've found something on stackoverflow about using a namespace like in the following code:
namespace myNameSpace {
template <typename T>
void fct(void) {}
template <>
void fct<int>(void) {}
}
class MyClass {
public:
template <typename T>
static void fct(void) {
myNameSpace::fct<T>();
}
};
int main(void) {
MyClass::fct<int>();
return 0;
}
What am I doing wrong? Is it possible to make template specialization with member functions? If not, what is the best way to get around this? Is there a better way than using namespace to get around this?
Upvotes: 3
Views: 303
Reputation: 476940
Write the specialization after the class definition:
class MyClass
{
public:
template <typename T>
static void fct(void) {}
};
template <>
void MyClass::fct<int>() {}
Upvotes: 5