C++ Primer 读书笔记1(三)

2015-01-26 23:12:53 · 作者: · 浏览: 17
cases, the newstandard introduced a second type specifier, decltype, which returns the typeof its operand. The compiler analyzes the expression to determine its type butdoes not eva luate the expression:

decltype(f()) sum = x; // sum has whatever type f returns

The way decltypehandles top-level const and references differs subtly from the way auto does.When the expression to which we apply decltype is a variable, decltype returnsthe type of that variable, including top-level const and references:

const int ci = 0, &cj = ci; 
decltype(ci) x = 0; // x has type const 
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

decltypeand References

// decltype of an expression can be a reference type 
int i = 42, *p = &i, &r = i; 
decltype(r + 0) b;  // ok: addition yields an int; b is an (uninitialized) int 
decltype(*p) c;     // error: c is int& and must be initialized

// decltype of a parenthesized variable is always a reference 
decltype((i)) d;    // error: d is int& and must be initialized 
decltype(i) e;      // ok: e is an (uninitialized) int

Remember that decltype((variable )) (note,double parentheses) is always a reference type, but decltype( variable ) is areference type only if variable is a reference.