1、auto關鍵字
C++新標準引入auto關鍵詞,此auto與之前C語言的auto意義已經不一樣了。
這裏的auto是修飾未知變量的類型,編譯器會通過此變量的初始化自動推導變量的類型。
例如:auto i = 0 ;編譯器會通過“0”值,推導出變量i是整型。
如果初始值是引用,如:
int i = 4;
int &ri = i;
auto ai = ri;
通過應用是利用了ri指向的對象,所以ai的類型是int。也就是ai與i的類型是相同的。
另外,auto是忽略top-level const,而保留low-level const屬性。具體說明如下:
const int ci = i, &cr = ci;
auto b = ci; // b is an int (top-level const in ci is dropped)
auto c = cr; // c is an int (cr is an alias for ci whose const is top-level)
auto d = &i; // d is an int * (& of an int object is int *)
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能夠推導表達式或者函數的返回類型,但不對表達式求值。
例如:
decltype(f()) sum = x;
變量sum擁有f()的返回值類型。與auto不同,decltype能夠返回變量的top-level屬性,如果變量是引用,那麼decltype修飾的變量也是引用。例如:
const int ci = 0, &cj = ci;
decltype(ci) x = 0; // x has type const int
decltype(cj) y = x; // y has type const int & and is bound to x
decltype(cj) z; // error: z is a reference and must be initialized.
當表達式不是變量,而是可作爲左值的對象時,那麼decltype返回的時指向該對象類型的應用。
int *p = &i;
decltype(*p) pri = i;
decltype(p) pi = &i;
其中pri是int &類型,而pi是int *類型。decltype的推導結果還與給定的表達式的形式有關。如果對變量求類型,那麼decltype直接返回變量的類型;如果變量加括號後,那麼decltype返回的類型是引用,引用的類型就是該變量的類型。
decltype(i) e; // e is an int variable uninitialized
decltype((i)) d; // error: d is int & and must be initialized