I have a (free) function template that looks like this
template <typename T>
T get();
I now want to specialize this function for a class, which itself is a template. But my compiler doesn’t want to compile it, and I’m asking now if that is even possible and how I could achieve it. Just for the idea, the code could look as follows: (Doesn’t compile)
template <>
template <typename T>
foo_type<T> get<foo_type<T>>()
What you’re doing is called partial specialization of function template. But partial specialization of function template is not allowed. Overloading of function template is allowed, but in this case, it is not possible either, as the function has only return type, and overloading on return type is not allowed.
So the solution is this:
You could also use overloads if you define them to take one argument so as to make overload valid:
Note that the argument
static_cast<T*>(0)is used to help the compiler to select the correct overload. IfTis other thanfoo<U>, then the first overload will be selected as the type of the argument passed to it will beT*as opposed tofoo<U>*. IfTisfoo<U>, then the second overload will be selected by the compiler because it is more specialized, and can accept the argument passed to it which isfoo<U>*in this case.