Identifying primitive types in templates
I am looking for a way to identify primitives types in a template class definition.
I mean, having this class :
template<class T>
class A{
void doWork(){
if(T isPrimitiveType())
doSomething();
else
doSomethingElse();
}
private:
T *t;
};
Is there is any way to "implement" isPrimitiveType().
Solution 1:
UPDATE: Since C++11, use the is_fundamental
template from the standard library:
#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;
}
}
In order to save the function call overhead, use 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 {
// ...
}
}
As others have pointed out, you can save your time implementing that by yourself and use is_fundamental from the Boost Type Traits Library, which seems to do exactly the same.
Solution 2:
Boost TypeTraits has plenty of stuff.
Solution 3:
I guess this can do the job quite nicely, without multiple specializations:
# 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;
}
And the output is:
isPrimitiveType(Foo): false
isPrimitiveType(int): true
isPrimitiveType(char): true
isPrimitiveType(unsigned long long): true