C++11 新特性 之 decltype

返回值 decltype(表达式)

[返回值的类型是表达式参数的类型]


这个可也用来决定表达式的类型,就像Bjarne暗示的一样,如果我们需要去初始化某种类型的变量,auto是最简单的选择,但是如果我们所需的类型不是一个变量,例如返回值这时我们可也试一下decltype。


1. 如果这个表达式是个函数,decltype 给出的类型为函数返回值的类型。

  1. int add(int i, int j){ return i+j; }  
  2. decltype(add(5,6)) var = 5;//Here the type of var is return of add() -> which is int 并不会执行add
  3. 需要注意:如果 int ary[10] = {0};那么 decltype(ary) iary;则iary也是含有10 个元素的数组,而不是指针。


2.如果表达式是一个左值类型,那么 decltype 给出的类型为表达式左值引用类型。

  1. struct M { double x; };  
  2.   
  3. double pi = 3.14;  
  4. const M* m = new M();  
  5. decltype( (m->x) ) piRef = pi;  
  6.   
  7.     // Note: Due to the inner bracets the inner statement is evaluated as expression,  
  8.     // rather than member 'x' and as type of x is double and as this is lvale  
  9.     // the return of declspec is double& and as 'm' is a const pointer   
  10.     // the return is actually const double&.  
  11.     // So the type of piRef is const double&   view plaincopy


3.非常重要的标记一下,decltype 不会执行表达式而auto会,他仅仅推论一下表达式的类型。

  1. int foo(){}  
  2. decltype( foo() ) x; // x is an int and note that   
  3.                      // foo() is not actually called at runtime   view plaincopy


4.跟踪返回类型:

  1. template<class U, class V>  
  2. auto Multiply(U u, V v) -> decltype(u*v)    // Note -> after the function bracet.  不要忘记这句话
  3. {   
  4.    return u*v;  
  5. plain


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值