3

I have code such as

template <class T> class Widget
{
    void fun() {}
}

//Okay: specialization of a member function of widget
template <> void Widget<char>:: fun() 
{
  void fun() {}
}

But, below is error as I am been told. But not understand why.

template<class T, class U> class Gadget
{
  void fun() {}
}

//Error! cannot partially specialize a member function of Gadget
template<class U> void Gadget<char,U>::fun()
{
  ..specialized implementation
}

Why is the second wrong? how to change it to make it right? thanks!!!!

BufBills
  • 8,005
  • 12
  • 48
  • 90

2 Answers2

3

It is impossible to partially specialize just one single member function, you have to partially specialize the whole class. That's how things work in C++.

The reason is that you cannot have partially specialized functions, and member functions are themselves functions. By partially specializing the whole class, the member functions will "look" like templates with fewer types (in that partial specialized class).

Why you cannot have partially specialized functions is another story, and I don't have a good answer/understanding why is this enforced.

About making it work, why don't you partially specialize the class, then re-define only the function that you need.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

One approach is to move that single function to a helper class template, which can be partially specialized:

template<class T, class U> class Gadget;

template<class T, class U>
struct Gadget_fun
{
    static void do_it(Gadget<T,U>* This) {}
};

template<class T, class U> class Gadget
{
    friend class Gadget_fun<T,U>;
    void fun() { Gadget_fun<T,U>::do_it(this); }
};

template<class U>
struct Gadget_fun<char, U>
{
    static void do_it(Gadget<char,U>* This)
    {
      //..specialized implementation
    }
};

This way you don't have to duplicate all the other members as you would to specialize Gadget itself.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720