在模板中标识原始类型 [英] Identifying primitive types in templates

查看:113
本文介绍了在模板中标识原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来识别模板类定义中的原始类型。

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;
    }
 }


$ b $ p

为了保存函数调用开销, :

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 {
        // ...
    }
}

正如其他人所指出的,自己和使用is_fundamental从Boost类型特征库,这似乎做同样的。

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.

这篇关于在模板中标识原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆