c++中的typeid和typeof

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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值