template<typename T>
class TestClass
{
public:
template<typename R = unsignedint>
R foo() const;
};
template<typename T>
template<typename R>
R TestClass<T>::foo() const
{
return R(0);
}
template<>
template<typename R>
R inline TestClass<char>::foo() const
{
return R(1);
}
template<>
template<typename R>
R inline TestClass<wchar_t>::foo() const
{
return R(2);
}
int main()
{
TestClass<char> testClass;
testClass.foo();
return 0;
}
Is there anything I can do to deduce the type specified on line 5 without modifying line 33, or would I have to define another template function outside of the class? This error only occurs when the function is specialized.
edit: This seems to work, but is there a way without defining another function?
If you're writing a function template, prefer to write it as a single function template that should never be specialized or overloaded, and implement the function template entirely in terms of a class template. This is the proverbial level of indirection that steers you well clear of the limitations and dark corners of function templates. This way, programmers using your template will be able to partially specialize and explicitly specialize the class template to their heart's content without affecting the expected operation of the function template. This avoids both the limitation that function templates can't be partially specialized, and the sometimes surprising effect that function template specializations don't overload.
- Sutter http://www.gotw.ca/publications/mill17.htm