Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying primitive types in templates

Tags:

c++

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().

like image 235
Ben Avatar asked Feb 24 '09 08:02

Ben


People also ask

Which of the data types are supported by template?

All data types, both primitive and compound types, must be defined by using a template.

Which of the following is a primitive types?

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.

What does primitive type mean?

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.

Is date a primitive type?

Date (which maps to System. DateTime ) is a primitive type of the Visual Basic .


1 Answers

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.

like image 143
Ferdinand Beyer Avatar answered Sep 25 '22 10:09

Ferdinand Beyer