C++11 auto and decltype

1、auto关键字

C++新标准引入auto关键词,此auto与之前C语言的auto意义已经不一样了。

这里的auto是修饰未知变量的类型,编译器会通过此变量的初始化自动推导变量的类型。

例如:auto i = 0 ;编译器会通过“0”值,推导出变量i是整型。

如果初始值是引用,如:

 

[cpp] view plain copy
 
  1. int i = 4;   
  2. int &ri = i;   
  3. auto ai = ri;  


通过应用是利用了ri指向的对象,所以ai的类型是int。也就是ai与i的类型是相同的。

 

另外,auto是忽略top-level const,而保留low-level const属性。具体说明如下:

 

[cpp] view plain copy
 
  1. const int ci = i, &cr = ci;  
  2. auto b = ci;    // b is an int (top-level const in ci is dropped)  
  3. auto c = cr;    // c is an int (cr is an alias for ci whose const is top-level)  
  4. auto d = &i;    // d is an int * (& of an int object is int *)  
  5. auto e = &ci;   // e is const int * (& of a const object is low-level const)  

上面的变量b、c、d、e说明了auto的一个特别属性,该特性与下面将要介绍的另一个关键字decltype不同。

 

为了实现top-level const,需要在auto前面加const,也就是const auto f = ci,那么f就是const int 类型。


2、decltype

关键字decltype能够推导表达式或者函数的返回类型,但不对表达式求值。  

例如:

 

[cpp] view plain copy
 
  1. decltype(f()) sum = x;  


变量sum拥有f()的返回值类型。与auto不同,decltype能够返回变量的top-level属性,如果变量是引用,那么decltype修饰的变量也是引用。例如:

 

 

[cpp] view plain copy
 
  1. const int ci = 0, &cj = ci;  
  2. decltype(ci) x = 0;    // x has type const int  
  3. decltype(cj) y = x;    // y has type const int & and is bound to x  
  4. decltype(cj) z;        // error: z is a reference and must be initialized.  

当表达式不是变量,而是可作为左值的对象时,那么decltype返回的时指向该对象类型的应用。

 

[cpp] view plain copy
 
  1. int *p = &i;  
  2. decltype(*p) pri = i;  
  3. decltype(p) pi = &i;  

其中pri是int &类型,而pi是int *类型。

 

decltype的推导结果还与给定的表达式的形式有关。如果对变量求类型,那么decltype直接返回变量的类型;如果变量加括号后,那么decltype返回的类型是引用,引用的类型就是该变量的类型。

 

 

[cpp] view plain copy
 
  1. decltype(i) e;     // e is an int variable uninitialized  

 

  1. decltype((i)) d;  // error: d is int & and must be initialized   

原:http://blog.csdn.net/hjx5200

 

 

posted @ 2016-06-29 21:55  Chris_z  阅读(372)  评论(0编辑  收藏  举报