简体   繁体   中英

specialization of static method template in class template

is there a 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 counts as a partial template specialization of a function?

As others have pointed out in the comments and link, the current C++ template syntax provides no easy way to support this usage. However, if you really want to do this and you don't mind introducing some complexity read on.

The two main problems you have to deal with are:

  1. function templates don't support partial specialization.
  2. partial specialization doesn't work when you define it as part of a class scope.

To get around them and get close to what you're looking for here's what you can try.

  • move the template definition outside of the class.
  • define those templates as class functors instead to permit partial spec'ing.

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'
}

That's an awful lot of extra code introduced for something like this but I suppose if you want to do this bad enough it's a possibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM