77、类型推导
C++ 提供了 auto 和 decltype 来静态推导类型,在我们知道类型没有问题但⼜不想完整地写 出类型的时候, 便可以使⽤静态类型推导。
for(vector<int>::const_iterator it = v.begin(); it != v.end(); ++it);
// 可以改写为
for(auto it = v.begin(); it != v.end(); ++it);虽然写起来和动态语⾔(如JavaScript的 var )很像,但C++仍然是强类型的,会执⾏静态类型检查的语⾔。这只是语法上的简化,并未改变C++的静态类型检查。
decltype ⽤于获取⼀个表达式的类型,⽽不对表达式进⾏求值(类似于sizeof)。 decltyp(e) 规则如下:
若 e 为⼀个⽆括号的变量、函数参数、类成员,则返回类型为该变量/参数/类成员在源程 序中的声明类型;
否则的话,根据表达式的值分类(value categories),设 T 为 e 的类型: 若 e 是⼀个左值(lvalue,即“可寻址值”),返回 T& ; 若 e 是⼀个临终值(xvalue),则返回值为 T&& ; 若 e 是⼀个纯右值(prvalue),则返回值为 T 。
const std::vector<int> v(1);
const int&& foo(); // 返回临终值:⽣命周期已结束但内存还未拿⾛
auto a = v[0]; // a 为 int
decltype(v[0]) b = 0; // b 为 const int&
// 即 vector<int>::operator[](size_type) const 的
返回值类型
auto c = 0; // c, d 均为 int
auto d = c;
decltype(c) e; // e 为 int,即 c 的类型
decltype((c)) f = e; // f 为 int&,因为 c 是左值
decltype(0) g; // g 为 int,因为 0 是右值Last updated