我们很难,甚至不可能提前知道一个表达式的 type,所以新标准引入了 auto and decltype.

auto

  • must have an initializer. because the compiler will deduce the type according to initializer.
  • when mulitiple declaration, each type should have same base type.
  • other use in function return “Array” Shortcuts by auto
  • other use in function return “Func” Shortcuts by auto
auto i = 0, *p = &i;      // ok
auto sz = 0, pi = 3.14;   // error
auto p2 = &i;             // ok

Exception for Deducing Compound Types and const

auto ordinarily ignores top-level consts, and low-level const is kept. If low-level is ignored, we can change the underlain.

int i = 0;
const int ci = i;
auto &g = ci;        // ok: g is const int& that is bound to ci
auto *p = &ci;       // ok: p is pointer to const int
auto &h = 42;        // error: 
const auto &j = 42;  // ok

Why the const is not ignored? 这其实是 compound type 的特性,不带个 const 就能改 underlain 了

Deduce Array Type?

^801e45

decltype

Actually, decltype is an operator, which returns the type of its operand. If the operand is a expression, then will not evaluate the expression.

auto 不同,decltype 给什么回什么,但还是有小例外

decltype and References

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((i)) d;   // error: d is int& and must be initialized
decltype(i) e;     // ok: e is an (uninitialized) int