关于 this site有以下段落:
When defining a member of an explicitly specialized class template outside the body of the class, the syntax template <> is not used, except if it's a member of an explicitly specialized member class template, which is specialized as a class template, because otherwise, the syntax would require such definition to begin with template< parameters > required by the nested template.
我不知道突出显示的部分是什么意思。 “否则”是指一般情况(不使用 template<>)还是异常(exception)情况(必须使用 template<>)?
我将不胜感激该部分的解释。
最佳答案
这将是我们的模板:
template< typename T>
struct A {
struct B {}; // member class
template<class U> struct C { }; // member class template
};
请看下面的代码:
template<> // specialization
struct A<int> {
void f(int); // member function of a specialization
};
// template<> not used for a member of a specialization
void A<int>::f(int) { /* ... */ }
我们没有使用 template<>
同时定义特化的成员,因为这是一个普通的成员类。
但是,现在看下一段代码:
template<> // specialization of a member class template
template<class U> struct A<char>::C {
void f();
};
// template<> is used when defining a member of an explicitly
// specialized member class template specialized as a class template
template<>
template<class U> void A<char>::C<U>::f() { /* ... */ }
这里我们特化了定义模板的成员模板。这就是为什么我们需要使用 template<>
传递此成员模板需要的参数。在这种情况下 class U
需要定义我们的成员模板,所以为了传递我们需要关键字 template<>
.
关于C++ 成员模板特化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792751/