1.typeid
C++中的typeid是由C++标准库提供,定义于<typeinfo>头文件,用于判断某个变量的类型。用法如下:
#include <typeinfo>
#include <iostream>
struct MyStruct
{
int a;
double b;
char c;
};
int main(int argc, char * argv[])
{
int num = 100;
if (typeid(int) == typeid(num))
{
std::cout << typeid(num).name() << std::endl;
}
MyStruct st{ 12, 12.34, 'A' };
if (typeid(MyStruct) == typeid(st))
{
std::cout << typeid(st).name() << std::endl;
}
return 0;
}
注:采用const标识或使用typedef定义的类型别名均不影响类型。
2.typeof
typeof由编译器提供(目前仅gcc编译器支持),用于返回某个变量或表达式的类型,C++11标准新增的decltype是typeof的升级版本。
a、取表达式的值的类型:
template< class A, class B>
function operator*(A a, B b) -> typeof(a*b); // return type last
// big change: function keyword
// : and return are obvious alternatives for ->
template< class A, class B>
typeof(a*b) operator* (A a, B b) ; // “lookahead parsing”
typeof(a*b)并不真的计算a*b的值,而是获得计算的结果的类型。
b、取表达式的类型:
template< class A, class B>
typeof(A*B) operator*(A a, B b); // use typenames
// not general
template< class A, class B>
typeof((*(A*)0)*(*(B*)0)) operator*(A a, B b); // hack