识别模板中的原始类型

2021-12-13 00:00:00 templates c++

我正在寻找一种方法来识别模板类定义中的基元类型.

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.

相关文章