Identifying primitive types in templates(识别模板中的原始类型)
问题描述
我正在寻找一种方法来识别模板类定义中的基元类型.
I am looking for a way to identify primitives types in a template class definition.
我的意思是,有这门课:
I mean, having this class :
template<class T>
class A{
void doWork(){
if(T isPrimitiveType())
doSomething();
else
doSomethingElse();
}
private:
T *t;
};
有什么方法可以实现"isPrimitiveType().
Is there is any way to "implement" isPrimitiveType().
推荐答案
UPDATE:从 C++11 开始,使用 is_fundamental
来自标准库的模板:
UPDATE: Since C++11, use the is_fundamental
template from the standard library:
#include <type_traits>
template<class T>
void test() {
if (std::is_fundamental<T>::value) {
// ...
} else {
// ...
}
}
<小时>
// Generic: Not primitive
template<class T>
bool isPrimitiveType() {
return false;
}
// Now, you have to create specializations for **all** primitive types
template<>
bool isPrimitiveType<int>() {
return true;
}
// TODO: bool, double, char, ....
// Usage:
template<class T>
void test() {
if (isPrimitiveType<T>()) {
std::cout << "Primitive" << std::endl;
} else {
std::cout << "Not primitive" << std::endl;
}
}
为了节省函数调用开销,使用结构体:
In order to save the function call overhead, use structs:
template<class T>
struct IsPrimitiveType {
enum { VALUE = 0 };
};
template<>
struct IsPrimitiveType<int> {
enum { VALUE = 1 };
};
// ...
template<class T>
void test() {
if (IsPrimitiveType<T>::VALUE) {
// ...
} else {
// ...
}
}
正如其他人指出的那样,您可以节省自己实现的时间,并使用 Boost Type Traits 库中的 is_fundamental,这似乎完全相同.
As others have pointed out, you can save your time implementing that by yourself and use is_fundamental from the Boost Type Traits Library, which seems to do exactly the same.
这篇关于识别模板中的原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:识别模板中的原始类型


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01