c++templatesstandardslanguage-lawyerexplicit-specialization

Why is explicit specialization of a member not allowed without specializing the class?


The C++ standard states the following:

In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well. (14.7.3/16 since C++11 and 14.7.3/18 in older standards)

This means that the following is not possible:

template<typename T>
class foo {
  template<typename U>
  void bar();
};

template<typename T>
template<>
void foo<T>::bar<some_type>(){
}

There have already been multiple questions of people having problems related to this, which were answered more or less by "the standard says so". What I don't really understand is why this restriction exists.


Solution

  • Thanks to JohnB for the answer:

    In the case, where there is one specialization for only the class (e.g. T=int), and another specialization for only the member (e.g. U=int), it would be impossible to decide, which specialization to use.

    Another point by skyjpack:

    There could be a class specialization without the member function.