识别模板中的基元类型

Ben*_*Ben 24 c++ templates

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

我的意思是,有这个课:

template<class T>
class A{
void doWork(){
   if(T isPrimitiveType())
     doSomething();
   else
     doSomethingElse(); 
}
private:
T *t; 
};
Run Code Online (Sandbox Code Playgroud)

有没有办法"实现"isPrimitiveType().

Fer*_*yer 28

更新:从C++ 11开始,使用is_fundamental标准库中的模板:

#include <type_traits>

template<class T>
void test() {
    if (std::is_fundamental<T>::value) {
        // ...
    } else {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)
// 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;
    }
 }
Run Code Online (Sandbox Code Playgroud)

为了保存函数调用开销,请使用结构:

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 {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

正如其他人所指出的那样,你可以节省你自己实现它的时间,并使用Boost Type Traits Library中的is_fundamental,这似乎完全相同.


Ant*_*lev 6

Boost TypeTraits有很多东西.


Rub*_*ens 5

我想这可以很好地完成这项工作,没有多个专业化:

# include <iostream>
# include <type_traits>

template <class T>
inline bool isPrimitiveType(const T& data) {
    return std::is_fundamental<T>::value;
}

struct Foo {
    int x;
    char y;
    unsigned long long z;
};


int main() {

    Foo data;

    std::cout << "isPrimitiveType(Foo): " << std::boolalpha
        << isPrimitiveType(data) << std::endl;
    std::cout << "isPrimitiveType(int): " << std::boolalpha
        << isPrimitiveType(data.x) << std::endl;
    std::cout << "isPrimitiveType(char): " << std::boolalpha
        << isPrimitiveType(data.y) << std::endl;
    std::cout << "isPrimitiveType(unsigned long long): " << std::boolalpha
        << isPrimitiveType(data.z) << std::endl;

}
Run Code Online (Sandbox Code Playgroud)

输出是:

isPrimitiveType(Foo): false  
isPrimitiveType(int): true  
isPrimitiveType(char): true  
isPrimitiveType(unsigned long long): true
Run Code Online (Sandbox Code Playgroud)