C++11 auto, decltype类型推断分析

auto

顶层const(指针本身指向不变, 如int *const)

	int y = 5;
    auto a1 = y;	//int
    auto a2 = &y;	//int*
    const auto a3 = &y; //int* const
    auto const a4 = &y;	//同上

底层const(指向的变量其本身不变, 如const int)

const int y = 5;
//初始值5本身是int值,不会把const属性一起带过去,需要自行加上
auto a1 = y; //int
const auto a2 = y;	//const int

指针/引用

int x = 5;
int *y = &x;
int &z = x;

auto a1 = x; //int
auto a2 = y; //int*,y本身是个地址
auto a3 = z; //int,z可以看作x的别名
auto& a4 = z; //int&

decltype

顶层const(指针本身指向不变, 如int *const)

int x = 5;
int *const y = &x;
decltype(y) a1 = &x; //int *const 

底层const(指向的变量其本身不变, 如const int)

const int x = 5;
decltype(x) a2 = x; //const int

指针/引用

int x = 5;
int *y = &x;
int &z = x;

decltype(x) a1 = 7; //int
decltype(y) a2 = &a1 //int*
decltype(z) a3 = a1; //int&

ADD:

引用->类型:

可以通过+0的方法将引用去掉

decltype(z + 0) a3 = a1; //int

指针->引用:

对于指针,可以将其解引用来获得其引用类型

decltype(*y) a2 = a1 //int&

类型->引用:

如果需要从类型推断出引用,可多加一对括号:

decltype((x)) a1 = 7; //int&

总结

auto通过初始值推导类型,不保留const和引用,需要自行加上;

decltype可以访问到已有表达式的类型(如果表达式是函数,不需要调用函数),因此能够保留const和引用,而且还可以进行引用与类型之间的转换;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值