UPDATE는 : C++ 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;
}
}
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 Library에서 is_fundamental을 사용하십시오.
반대의 경우도 있습니다 :'std :: is_class'.https://stackoverflow.com/questions/11287043/is-there-a-way-to-specialize-a-template-to-target-primitives –