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().
All data types, both primitive and compound types, must be defined by using a template.
Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double . These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind.
A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: byte: The byte data type is an 8-bit signed two's complement integer.
Date (which maps to System. DateTime ) is a primitive type of the Visual Basic .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With