Ryan Brown
Ryan Brown

Reputation: 1085

C++ templates and basic data types

Is there any way to tell if a template parameter is a specific base data type like int or unsigned int? std::is_base_of doesn't do it, tried that. I'd like to write collections that can box all the basic data types but I can't find a way to tell which type it is...

Upvotes: 1

Views: 185

Answers (4)

juanchopanza
juanchopanza

Reputation: 227418

If you want to know whether it is of a specific type, you could use std::is_same:

#include <type_traits>

bool isInt = std::is_same<int, T>::value;

If you wanted to know whether it is any integral type, the std::is_integral

bool isInt = std::is_integral<T>::value;

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40859

Use is_same. If you don't have an implementation (std or boost) then use this:

template < typename T1, typename T2 >
struct is_same { enum { value = false }; };

template < typename T >
struct is_same <T,T> { enum { value = true }; };

Upvotes: 3

jrok
jrok

Reputation: 55395

Some useful ones:

std::is_integral

std::is_floating_point

std::is_arithmetic

If you need some more narrow definiton, you can OR several std::is_same traits together, e.g.

template<typename T>
struct is_int_or_char_or_float {
    static const bool value =
        std::is_same<T, int>::value ||
        std::is_same<T, char>::value ||
        std::is_same<T, float>::value;
};

Upvotes: 2

KhalidTaha
KhalidTaha

Reputation: 473

you can use this code:

#include <typeinfo>
#include <iostream>

class someClass { };

int main(int argc, char* argv[]) {
    int a;
    someClass b;
    std::cout<<"a is of type: "<<typeid(a).name()<<std::endl; // Output 'a is of type int'
    std::cout<<"b is of type: "<<typeid(b).name()<<std::endl; // Output 'b is of type someClass'
    return 0;
}

Upvotes: 0

Related Questions