Search code examples
c++templatesc++14variadic-templatesc++-templates

Template member function cannot be explicitly specialized


I have a declaration of a function in class

class A { 
  template<typename T, typename... ARGS>
  void Func( ARGS&&... args) {
     //DoSomeWork
  }
};

and then try to specialize it for some type like this

template<>
void A::Func<int>(bool arg) {
//DoSomeOtherWork
}

I get error

error C2910: 'A::Func': cannot be explicitly specialized

Is there a way to specialize the template or do I have to find a workaround? If there is no way to specialize the template, why is that the case?


Solution

  • Specialization can't change argument types. If Func (the primary template) accepts parameters by reference, the specialization must do so too, e.g.:

    template<>
    void A::Func<int>(bool &&arg) {}
    

    Also MSVC is being suprisingly unhelpful in this case. Clang does a better job:

    <source>:9:9: error: no function template matches function template specialization 'Func'
        9 | void A::Func<int>(bool arg) {
          |         ^
    <source>:3:8: note: candidate template ignored: could not match 'ARGS &&' against 'bool'
        3 |   void Func( ARGS&&... args) {
          |        ^