[英]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? 有什么方法可以判断模板参数是特定的基础数据类型(例如int还是unsigned int)? std::is_base_of doesn't do it, tried that.
std :: is_base_of不这样做,尝试了一下。 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. 使用is_same。 If you don't have an implementation (std or boost) then use this:
如果您没有实现(std或boost),请使用以下代码:
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: 一些有用的:
If you need some more narrow definiton, you can OR several std::is_same
traits together, eg 如果您需要一些更狭窄的定义,则可以将几个
std::is_same
特征一起或在一起,例如
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
: 如果您想知道它是否为特定类型,可以使用
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
如果您想知道它是否为整数类型,请使用
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.