36

I am reading the Complete Guide on Templates and it says the following:

Where it is talking about class template specialization.

Although it is possible to specialize a single member function of a class template, once you have done so, you can no longer specialize the whole class template instance that the specialized member belongs to.

I'm actually wondering how this is true, cause you can specialize without any member functions at all. Is it saying that you cannot have a specialization with only one member function and then another with all member functions?

Can someone please clarify?

rahul.deshmukhpatil
  • 939
  • 1
  • 16
  • 31
Tony The Lion
  • 59,704
  • 62
  • 233
  • 403

2 Answers2

38

I think it is referring to the following case:

template <typename T>
struct base {
   void foo() { std::cout << "generic" << std::endl; }
   void bar() { std::cout << "bar" << std::endl; }
};
template <>
void base<int>::foo() // specialize only one member
{ 
   std::cout << "int" << std::endl; 
}
int main() {
   base<int> i;
   i.foo();         // int
   i.bar();         // bar
}

Once that is done, you cannot specialize the full template to be any other thing, so

template <>
struct base<int> {};  // error
David Rodríguez - dribeas
  • 198,982
  • 21
  • 284
  • 478
  • You should perhaps note that if you *don't* just specialize the member and you use the full template specialization you have above, the *specialization* is still valid - the calling code that depends on `foo` and `bar` being there no longer is. I.e., the same code you posted above, modified to not specialize the member and not call `foo` and `bar` will work fine - see http://ideone.com/3kHa3 – rlc May 10 '11 at 12:59
  • so I guess this one member specialization creates an instance and therefore you can no longer have another specialization? – Tony The Lion May 10 '11 at 13:12
  • 11
    @Tony - Right, but you can of course have another specialization for a different type, like `base`. – Bo Persson May 10 '11 at 13:40
3

I think what is meant is that you can either:

  • specialize the whole class and all members (data and functions, static or not, virtual or not) have to be declared and defined even if they are the same as for the non specialized version,

  • specialize some function members, but then you can't specialize the whole class (i.e. all members are declared in the same way as for the non specialized case, you just provide the implementation for some function members).

AProgrammer
  • 49,582
  • 8
  • 87
  • 140