Given the following:
class MyClass
{
public:
template <typename T, typename U = T>
void doSomething(T) {}
private:
double parser;
};
template<>
inline void MyClass::doSomething<bool>(bool) {}
template<>
inline void MyClass::doSomething<int, double>(int) {}
int main(int argc, char* argv[])
{
MyClass foo;
foo.doSomething<bool>(true);
foo.doSomething<int, double>(10);
return 0;
}
This works fine.
However now I want to introduce a class template in order to use a template parameter instead of ParserClass
, like so:
template<typename P>
class MyClass
{
public:
template <typename T, typename U = T>
void doSomething(T) {}
private:
P parser;
};
template<>
inline void MyClass::doSomething<bool>(bool) {}
template<>
inline void MyClass::doSomething<int, double>(int) {}
int main(int argc, char* argv[])
{
MyClass<double> foo;
foo.doSomething<bool>(true);
foo.doSomething<int, double>(10);
return 0;
}
Which, however, does no longer work:
test.cpp:12:13: error: 'MyClass' is not a class, namespace, or enumeration
inline void MyClass::doSomething<bool>(bool) {}
^
test.cpp:2:7: note: 'MyClass' declared here
class MyClass
^
1 error generated.
Is it even possible? How do I combine the member function template parameters and the class template parameters in the above example?
To specialize a function that is a member of a templated class, you need two template<>
declarations. Furthermore, you need to specify the typename
for MyClass
:
template<> template<>
inline void MyClass<some_type>::doSomething<bool>(bool) { ... }
template<> template<>
inline void MyClass<some_type>::doSomething<int, double>(int) { ... }