本文介绍了识别模板中的原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我正在寻找一种方法来识别模板类定义中的基元类型.
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.
这篇关于识别模板中的原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)