I need to specialize template member function for some type (let's say double). It works fine while class X
itself is not a template class, but when I make it template GCC starts giving compile-time errors.
#include <iostream>
#include <cmath>
template <class C> class X
{
public:
template <class T> void get_as();
};
template <class C>
void X<C>::get_as<double>()
{
}
int main()
{
X<int> x;
x.get_as();
}
here is the error message
source.cpp:11:27: error: template-id
'get_as<double>' in declaration of primary template
source.cpp:11:6: error: prototype for
'void X<C>::get_as()' does not match any in class 'X<C>'
source.cpp:7:35: error: candidate is:
template<class C> template<class T> void X::get_as()
How can I fix that and what is the problem here?
Thanks in advance.
It doesn't work that way. You would need to say the following, but it is not correct
Explicitly specialized members need their surrounding class templates to be explicitly specialized as well. So you need to say the following, which would only specialize the member for
X<int>
.If you want to keep the surrounding template unspecialized, you have several choices. I prefer overloads
If one is able to used
std::enable_if
we could rely on SFINAE (substitution failure is not an error)that would work like so:
The ugly thing is that, with all these enable_if's only one specialization needs to be available for the compiler otherwise disambiguation error will arise. Thats why the default behaviour "get as T" needs also an enable if.