c++ - 当我在 C++ 中对类模板进行完全特化时,为什么我不必定义相同的成员?

标签 c++ templates template-specialization

我很惊讶地发现以下编译:

#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/

相关文章:

c++ - 在具有父 ID 的一般树中找到最低公共(public)祖先

c++ - 我可以在GDB中的 'memory access'处设置断点吗?

c++ - vector 的 vector 的 vector 之和......整数

c++ - 如何通过未定义类型定义元函数?

c++ - 在编译时选择使用模板调用的函数

c++ - 有 C++ MinMax Heap 实现吗?

c++ - Windows是否有自己的 'call other .exe'函数(C++)

c++ - 提供适当的 operator<< 和可变模板特化

c++ - 使用可调用参数重载可调用

c++ - 创建显式专用模板类对象会产生 "object has initializer but incomplete type"错误