I have a template class and a template member function:
template<class T1>
struct A{
template<class T2>
static int f(){return 0;}
};
I want to specialize for a case when T1
and T2
are the same,
For example, define the case A<T>::f<T>
for any T
.
but I can't find the combination of keywords to achieve this.
How can I partially (?) specialize a combination of template class and a template static function?
These are my unsuccessful attempts, and the error messages:
1) Specialize inside the class: fatal error: cannot specialize a function 'f' within class scope
)
template<class T1>
struct A{
template<class T2>
static int f(){return 0;}
template<>
static int f<T1>(){return 1;}
};
2) Specialize outside the class "simultaneously": fatal error: cannot specialize a member of an unspecialized template
template<class T>
void A<T>::f<T>(){return 1;}
3) Specialize using template<>
: fatal error: too few template parameters in template redeclaration
template<> template<class T>
void A<T>::f<T>(){return 1;}
4) Invert the order: fatal error: cannot specialize (with 'template<>') a member of an unspecialized template
template<class T> template<>
void A<T>::f<T>(){return 1;}
5) Specialize the whole class (based on the error of attempt 3): fatal error: class template partial specialization does not specialize any template argument; to define the primary template, remove the template argument list
template<class T>
struct A<T>{
template<>
static int f<T>(){return 1;}
};
6) Specialize the class but not the function (?): fatal error: too few template parameters in template redeclaration
template<> template<class T1>
template<> template<class T>
int A<T>::f(){return 0;}
I used clang 3.5 C++14
to generate the error messages.
You cannot partially specialize a function.
You can forward the work to another type:
or, more simply, with no
A_helper
:you can use tag dispatching.
Another approach:
where we directly dispatch on the type of
T2
.