【发布时间】:2019-01-21 02:26:05
【问题描述】:
类模板的成员或成员模板可以显式专门用于类模板的给定隐式实例化...
经过一些测试,我发现特化应该与类模板的隐式实例化中的成员匹配,这意味着它们应该是相同的类型。例如,
template<class T> struct A {
void f(T);
static T i;
};
template<> void A<int>::f(int); // ok
// template<> void A<int>::f(char); // error
template<> int A<int>::i; // ok
// template<> char A<int>::i; // error
标准在哪里指定了此类约束?
【问题讨论】:
-
如果
template<class T>和void f(T)中有相同的T,那么Ts怎么可能不同? -
除了 Evgeny:为类型
int实例化struct A,您还定义了一个方法void f(int);。如果你想实现template<> void A<int>::f(char) { }- 在struct A<int>中没有定义这样的方法。如果你需要这个,你必须完全专门化template <class T> struct A,例如template <> struct A<int> { void f(char); };现在,您可以(必须)实现void A<int>::f(char) { }。替代方案:将 quest 中的方法设为自己的模板:template <class T> struct A { template <class U = T> void f(U); }。 -
方法
f(T)本身不是模板——它是template struct A的一部分。你不能专门化不是模板的东西,对吧。 (对不起,这也不是“语言律师”评论。) -
请记住,模板的最初想法是将类型设置为参数。在每次出现时插入任意类型并不是一个纯粹的占位符。
-
您不能专门化非模板。 (......我可以想象你在标准中找不到任何引用。)只是你可以专门化模板(而不是别的)。
标签: c++ templates language-lawyer template-specialization