我已阅读 What does template's implicit specialization mean?和它的答案,但我仍然不满意我理解这部分Partial template specialization来自 cppreference.com:
If the primary member template is explicitly (fully) specialized for a given (implicit) specialization of the enclosing class template, the partial specializations of the member template are ignored for this specialization of the enclosing class template....
template<class T> struct A { //enclosing class template template<class T2> struct B {}; //primary member template template<class T2> struct B<T2*> {}; // partial specialization of member template }; template<> template<class T2> struct A<short>::B {}; // full specialization of primary member template // (will ignore the partial) A<char>::B<int*> abcip; // uses partial specialization T2=int A<short>::B<int*> absip; // uses full specialization of the primary (ignores partial) A<char>::B<int> abci; // uses primary
问题:
template<> template<classT2> struct A<short>::B {};
是“主要成员模板的完全特化”。主要成员模板在注释中标识为结构 B
.线怎么会是B
的专业当它是A
正在通过替换 short
专门化为 class T
?B
当模板参数T2
未指定?B
的显式特化,其中是 A
的隐式特化?最佳答案
类模板的成员可以显式特化,即使它是 不是模板 :
template<int I>
struct X {
int f() {return I;}
void g() {}
};
template<>
int X<0>::f() {return -1;}
这相当于专门化了整个类模板,但具有其他成员 重复 来自相关的主要模板或部分特化:template<>
struct X<0> {
int f() {return -1;}
void g() {}
};
(回想一下,这样一个拼写出来的特化完全没有义务声明 g
或作为一个函数。)因为你实际上没有写这个,它仍然被认为是一个 隐式 X
的实例化作为一个整体与给定的改变。这就是为什么您的特化
A<T>::B
为 A
提供模板参数而不是为 B
;它是 更换 模板A<T>::B
与另一个模板(恰好具有相同的模板参数列表)。我会说“主要”这个词在这里有误导性:它是整个模板被替换,这就是为什么 A<short>
忽略部分特化的原因。此后。
关于c++ - 这篇 cppreference.com 文章的结尾有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64507071/