Specialization of the static method template in the class template

Is there any way to make this code work?

template<typename T> class test{ public: template<typename T2> static void f(){ cout<<"generic"<<endl; } template<> static void f<void>(){ //specialization of static method for template T2, within generic class template with argument T cout<<"void"<<endl; } }; 

if not, is it because it is considered a partial specialization of the function template?

+3
source share
1 answer

As other comments and links have pointed out, the current syntax of C ++ templates does not provide an easy way to support this use. However, if you really want to do this, and you do not mind, to introduce some difficulty in reading.

Two main problems you have to deal with:

  • function templates do not support partial specialization.
  • partial specialization does not work if you define it as part of the scope of the class.

To get around them and get closer to what you are looking for, what you can try.

  • move the template definition outside the class.
  • define these patterns as functions of classes instead, to allow partial specification.

 template<typename T> class test { public: template <typename T2> static void f(); }; template <typename T1, typename T2> struct f { void operator ()(void) { cout << "generic" << endl; } }; template <typename T1> struct f<T1, void> { void operator ()(void) { cout << "void" << endl; } }; template <typename T> template <typename T2> void test<T>::f() { ::f<T, T2>()(); } int main() { test<int>::f<int>(); // prints 'generic' test<int>::f<void>(); // prints 'void' } 

This is a lot of extra code introduced for something like this, but I suppose if you want to do it badly enough, it is possible.

+4
source

All Articles