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.
这篇关于识别模板中的原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:识别模板中的原始类型


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01