CẬP NHẬT: Kể từ C++ 11, sử dụng is_fundamental
mẫu từ thư viện chuẩn:
#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;
}
}
Để tiết kiệm các chi phí chức năng cuộc gọi, sử dụng cấu trúc:
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 {
// ...
}
}
Như những người khác đã chỉ ra, bạn có thể tiết kiệm thời gian của mình tự thực hiện điều đó một mình và sử dụng is_fundamental từ Thư viện kiểu Boost Traits, có vẻ giống hệt như vậy.
Nguồn
2009-02-24 08:34:00
Cũng lưu ý rằng cuộc trò chuyện tồn tại: 'std :: is_class', ví dụ:https://stackoverflow.com/questions/11287043/is-there-a-way-to-specialize-a-template-to-target-primitives –