C++11:(二)decltype类型推导

decltype的功能和auto相同,都用来在编译时期进行自动类型推导。

两者区别如下:

auto varname = value;
decltype(exp) varname = value;
  • auto根据=右边的初始值value推导出变量的类型。
  • decltype根据exp表达式推导出变量类型,跟=右边的初始值value没有关系。

举例:

decltype(10.8) x = 5.5;  //x 被推导成了 double
decltype(x+100) y;   //y 被推导成了 double

decltype 推导规则

decltype(exp) varname;

① 如果exp是一个不被括号()包围的表达式,那么 decltype(exp) 的类型就和 exp 一致,这是最普遍最常见的情况。

int n = 0;
decltype(n) a = n;  //n 为 int 类型,a 被推导为 int 类型

② 如果exp是函数调用,那么decltype(exp)的类型就和 函数返回值 的类型一致。

int& func_int_r(int, char);  //返回值为 int&
decltype(func_int_r(100, 'A')) a = n;  //a 的类型为 int&

③ 如果 exp 是一个左值,或者被括号()包围,那么 decltype(exp) 的类型就是 exp 的引用。

int n = 0;
decltype((n)) a = b; //带有括号,符合推导规则三,a 的类型为 int&。

decltype 的实际应用

auto 的语法格式比 decltype 简单,所以在一般的类型推导中,使用 auto 比使用 decltype 更加方便。

但是,auto 只能用于 类的静态成员,不能用于 类的非静态成员(普通成员),如果我们想推导 非静态成员的类型,这个时候就必须使用 decltype 。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值