C++之类型萃取
在C++中想要获得某个变量的类型有两种方式:
一种是利用typeid。
typeid是C++的关键字之一,等同于sizeof这类的操作符。typeid操作符的返回结果是名为type_info的标准库类型的对象的引用。
用法:typeid().name()
#include <iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
Base b, *pb;
pb = NULL;
Derived d;
cout << typeid(int).name() << endl
<< typeid(unsigned).name() << endl
<< typeid(long).name() << endl
<< typeid(unsigned long).name() << endl
<< typeid(char).name() << endl
<< typeid(unsigned char).name() << endl
<< typeid(float).name() << endl
<< typeid(double).name() << endl
<< typeid(string).name() << endl
<< typeid(Base).name() << endl
<< typeid(b).name()<<endl
<< typeid(pb).name()<<endl
<< typeid(Derived).name() << endl
<< typeid(d).name()<<endl
<< typeid(type_info).name() << endl;
return 0;
}
另一种是利用类模板的特化,让编译器根据所传入变量的类型在调用对于特化类的函数时自动选择与之对应的类型
struct _TrueType{
static bool Get()
{
return true;
}
};
struct _FalseType{
static bool Get()
{
return false;
}
};
template <typename T>
struct TypeCheck{
typedef _FalseType IsPODType;
};
template<>
struct TypeCheck<int>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<char>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<float>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<short>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<long>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<long long>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<unsigned int>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<unsigned char>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<double>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<unsigned short>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<unsigned long>
{
typedef _TrueType IsPODType;
};
template<>
struct TypeCheck<unsigned long long>
{
typedef _TrueType IsPODType;
};
template< typename TE>
bool IsPodType(TE t)
{
return TypeCheck<TE>::IsPODType::Get();
}
int main()
{
long l = -1;
unsigned long ul = 0;
float f = 1.1;
double d = 1.1;
string s = "1";
char a[] = "1";
cout << IsPodType(1)<<endl;
cout << IsPodType("1")<<endl;
cout << IsPodType('1') <<endl;
cout << IsPodType(l) <<endl;
cout << IsPodType(ul) <<endl;
cout << IsPodType(f) <<endl;
cout << IsPodType(d) <<endl;
cout << IsPodType(s) <<endl;
cout << IsPodType(a) <<endl;
return 0;
}
运行结果: