为什么在不特化 class 的情况下不允许成员的显式特化?

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

C++ 标准规定如下:

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)

这意味着以下是不可能的:

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

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

已经有很多人提出了与此相关的问题,"the standard says so"都或多或少地回答了这些问题。我不太明白的是为什么存在这个限制。

感谢 JohnB 的回答:

在这种情况下,只有 class 有一个专业化(例如 T=int),而另一个专业化只有成员(例如 U=int),它将是无法决定使用哪个专业。

skyjpack 的另一点:

可以有一个没有成员函数的 class 特化。

模板函数在首次使用或特化时被实例化。

当你进行偏特化时,你不能实例化函数,因为它仍然是模板函数。因此,当您进行专门化时,编译器必须以某种方式了解您已经进行了部分实例化并将其与您的实例化相匹配,这可能会导致困难。

人们在评论中说,这会导致歧义,但很多事情都会导致歧义。例如,考虑重载函数。如果调用哪个重载函数不明确,编译器会告诉您。在这种情况下也是如此。