c++ 中auto与decltype

本文探讨了C++中auto和decltype两种类型推导方式的差异。通过示例代码展示它们在处理顶层const时的不同行为,以及在变量声明和表达式类型推导中的应用。auto通常忽略顶层const,而decltype会保留。此外,还解释了decltype如何根据表达式类型而非实际赋值来推导变量类型。

使用auto进行类型推导


#include<iostream>
using namespace std;
int main()
{
	const int i = 42;
	auto j = i;
	j = 1;
	cout<<j<<endl;				// auto一般会忽略顶层const 
	const auto &k = i;			// 明确指定为顶层const 
	//k = 1; 							// k是const引用 
	auto *p = &i;					// p的类型是const int*
	//int* pp = &i;					// invalid conversion from const int* to int*
	//*pp = 1; 
	p = 0;						
	*p = 1; 					
	 
	const auto j2 = i, &k2 = i;	// 同上 
	return 0;
 } 

使用decltype进行类型推导
在需要从表达式的类型推断出要定义的变量的类型,但是又不希望用表达式的值初始化要定义的变量时,可以用decltype。
如下

//important 
#include<iostream>
using namespace std;
int main()
{
	int a = 3, b = 4;
	decltype(a) c = a;		
	decltype(a = b) d = a;	// decltype并不会实际执行表达式 ,注意a=b的赋值操作产生引用类型
										// 产生的原因应该是内置的=操作符返回的是引用类型
	cout<<c<<endl;
	cout<<d<<endl;
	cout<<a<<endl;			// 表达式实际上没有被执行,a的值没有发生变化 
	d = 1;
	cout<<a<<endl;			// d是a的引用 
	cout<<d<<endl; 
	return 0;
 } 

输出:
在这里插入图片描述
在对拥有顶层const的变量进行类型推导时,auto和decltype的表现有所不一样,具体的,auto会忽略顶层const而decltype会保留顶层const。代码如下

// important 
// decltype推断时是否会忽略顶层const属性? 
#include<iostream>
using namespace std;
int main()
{
	const int a = 2;
	auto b = a;				// b是int类型 ,auto忽略了顶层const
	decltype(a) c = 5;	// c是const int类型,decltype保留了顶层const 
 	b = 8;
	//c = 9;						// 错误 assignment of read-only variable 'c' 
 	
	return 0;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值