简体   繁体   中英

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.

Thanks to JohnB for the answer:

In the case, where there is one specialization for only the class (eg T=int ), and another specialization for only the member (eg 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.

Template function is instantiated when it is first used or when it is specialized.

When you do partial specialization you can't instantiate function, as it is still template function. So when you do specialization, compiler somehow must understand that you already had partial instantiation and match it to your instantiation, which can lead to difficulties.

People say in the comments, that it can lead to an ambiguity, but a lot of things can lead to ambiguous things. Think of overloaded functions, for example. If it is ambiguous which overloaded function to call, compiler tells you about it. Same in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM