UPDATE: Dal momento che C++ 11, utilizzare il modello is_fundamental
dalla libreria standard:
#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;
}
}
Al fine di salvare l'overhead funzione di chiamata, utilizzare le strutture:
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 {
// ...
}
}
Come altri hanno sottolineato, puoi risparmiare tempo implementandolo da solo e usa is_fundamental dalla libreria Boost Type Traits, che sembra fare esattamente la stessa cosa.
fonte
2009-02-24 08:34:00
Si noti inoltre che l'inverso esiste: 'std :: is_class', ad es.https://stackoverflow.com/questions/11287043/is-there-a-way-to-specialize-a-template-to-target-primitives –