[英]Specializing Templatized Struct Inside Templatized Class
template <class T1, class T2>
class A {
template <typename T>
struct BarSelector {
void bar(T*) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
template <> struct BarSelector<D> {
void bar(D*) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
public:
void foo(T2* pT2) {
// do something
BarSelector<T2> selector;
selector.bar(pT2);
}
};
int main() {
C c;
A<B, C> a1;
a1.foo(&c);
D* pD;
A<B, D> a2;
a2.foo(pD);
}
Compiler gave: 编译器给出:
toverloading.cpp:20:11: error: explicit specialization in non-namespace scope ‘class A<T1, T2>’
template <> struct BarSelector<D> {
^
toverloading.cpp:20:20: error: template parameters not used in partial specialization:
template <> struct BarSelector<D> {
^
toverloading.cpp:20:20: error: ‘T1’
toverloading.cpp:20:20: error: ‘T2’
If I move the BarSelector outside class A, it works. 如果我将BarSelector移到A类之外,它将起作用。
What's the correct syntax to keep them inside class A? 将它们保留在A类中的正确语法是什么?
Thanks! 谢谢!
What's the correct syntax to keep them inside class A? 将它们保留在A类中的正确语法是什么?
No, explicit specialization can't be put in a class scope, it must be put in namespace scope. 不可以,显式专门化不能放在类范围内,而必须放在命名空间范围内。
From the standard, $14.7.3/2 Explicit specialization [temp.expl.spec] 根据标准,$ 14.7.3 / 2显式专门化[temp.expl.spec]
An explicit specialization shall be declared in a namespace enclosing the specialized template. 显式专门化必须在包含专门化模板的命名空间中声明。
So you have to move it outside the class, such as: 因此,您必须将其移至类之外,例如:
template<>
template<>
class A<B, D>::BarSelector<D> {
void bar(double*) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
Note that it's impossible to specialize a member without explicitly specializing the containing class. 请注意,如果不显式地专门化包含类,就不可能对成员进行专门化。 That might be a side note about why can't explicit specialize a member template in class scope (which let you specialize a member template without explicitly specializing the outside class template). 这可能是关于为什么不能在类范围内显式专门化成员模板的旁注(这使您可以专门化成员模板而不显式专门化外部类模板)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.