अद्यतन: सी ++ 11 के बाद से, मानक पुस्तकालय से is_fundamental
टेम्पलेट का उपयोग करें:
#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;
}
}
क्रम समारोह कॉल उपरि, उपयोग 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 {
// ...
}
}
जैसा कि अन्य ने बताया है, आप अपना समय बचा सकते हैं I अपने आप को पूरक और बूस्ट टाइप ट्रेट्स लाइब्रेरी से is_fundamental का उपयोग करें, जो वास्तव में वही करता है।
स्रोत
2009-02-24 08:34:00
ध्यान दें कि बातचीत भी मौजूद है: 'std :: is_class', उदा।https://stackoverflow.com/questions/11287043/is-there-a-way-to- specialize-a-template-to-target-primitives –