我很惊讶地发现以下编译:
#include <iostream>
using namespace std;
template<typename T>
class SomeCls {
public:
void UseT(T t) {
cout << "UseT" << endl;
}
};
template<>
class SomeCls<int> {
// No UseT? WTF?!??!?!
};
int main(int argc, char * argv[]) {
SomeCls<double> d;
SomeCls<int> i;
d.UseT(3.14);
// Uncommenting the next line makes this program uncompilable.
// i.UseT(100);
return 0;
}
为什么允许这样做? class SomeCls<int>
似乎是错误的不需要 void UseT(T t)
方法。我确定我错过了这里的特化点(我不是 C++ 专家)。谁能赐教一下?
最佳答案
因为 SomeCls<double>
是与 SomeCls<int>
完全不同的类型或任何其他 SomeCls<T>
.他们没有任何关系,所以他们可以拥有任何他们想要的成员。请务必不要调用 i.UseT()
,当然,这是编译器开始提示的地方。
关于c++ - 当我在 C++ 中对类模板进行完全特化时,为什么我不必定义相同的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6340117/