简体   繁体   中英

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

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 }; };

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, eg

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;
};

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;

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM