Home > OS >  Partial specialization for class method
Partial specialization for class method

Time:02-06

I'm trying to specialize a method of a (non-templated!) class. Apparently, it's not possible, however I am struggling to figure out why, or how to overcome the problem.

class MyClass {

public:
        template <typename... T>
        auto MyMethod(T... t) -> void { std::cout << "Original" << std::endl; }

        template <typename... T>
        auto MyMethod<int, T...>(int value, T... t) -> void { std::cout << "Specialization" << value << std::endl; }

};

int main(void) {
        MyClass myClass;
        myClass.MyMethod<char, char>('c', 'c');
        myClass.MyMethod<int, char>(123, 'c');

        return 0;
}

The error is as follows:

test.cpp:10:49: error: non-class, non-variable partial specialization ‘MyMethod<int, T ...>’ is not allowed
   10 |  auto MyMethod<int, T...>(int value, T... t) -> void { std::cout << "Specialization" << value << std::endl; }

It seems that there would be no reason for this to be impossible (with a template class it makes sense that the entire class has to be specialized too). What am I missing? Is it literally not possible?

CodePudding user response:

Only classes can be partially specialized; methods can only be fully specialized. As your methods still have template arguments (T) that are not specified, this means a partial method specialization.

If you would use these template arguments for a class (and call a non-templated member function of that class) then this should be possible.

  •  Tags:  
  • Related