c++ - 如何检查我的模板类是否属于特定类类型?

标签 c++ templates

在我的模板化函数中,我试图检查类型 T 是否属于特定类型。我该怎么做?

p/s 我知道模板规范方式,但我不想那样做。

template<class T> int foo(T a) {
  // check if T of type, say, String?
}

谢谢!

最佳答案

使用特化来代替检查类型。否则,请勿使用模板。

template<class T> int foo(T a) {
      // generic implementation
}
template<> int foo(SpecialType a) {
  // will be selected by compiler 
}

SpecialType x;
OtherType y;
foo(x); // calls second, specialized version
foo(y); // calls generic version

关于c++ - 如何检查我的模板类是否属于特定类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31251399/

相关文章:

c++ - 接受模板类的模板函数

c++ - boost::function 如何支持不同长度模板参数的模板类

c++ - 字符串的模板参数类型

scala - play 框架将子类传递给 scala 模板

c++ - 如何将模板类用于容器的容器?

Magento adminhtml 布局更新

c++ - 如何使用 STL 为数据点创建最大和最小堆?

c++ - 根据条件创建 shared_lock 或 unique_lock

c++ - 使用可重定位设备代码时的 CUDA 8.0 Visual Studio 2012 链接器选项

c++ - 使用模板时,如何解决以下编译器错误,以实现程序所需的行为?