《Effective Modern C++》Item 2总结

先提出两个基本观点:

1.auto和模板参数类型推导拥有几乎一模一样的规则,所以Item1总结的规则对于auto适用。

2.auto和模板参数了类型推导有一个不相同的地方,不同在于对于花括号的处理不同。为什么不同呢?王八屁股,规定!Scotter Meyer也不知道答案。

 

我们知道Item1 ,提出了三个不同的case:

1.类型描述符是指针或引用,并且不是全球通引用

2.类型描述符是全球通引用

3.类型描述符既不是指针,也不是引用

template<typename T> void f(ParamType param);

 



简单来看,我们可以把auto当成模板函数参数描述符里的 T。

const int x=5;



auto y=x;    //y is int.



auto yy= 5; //yy is int.



const auto cy = yy;

 

上面代码类型推导遵循case3,所有的auto类型都是int。

const auto& ry= yy;

 

上面代码遵循case1.

auto&& uref1 = x; // x is int and lvalue,

 // so uref1's type is int&

auto&& uref2 = cx; // cx is const int and lvalue,

 // so uref2's type is const int&

auto&& uref3 = 27; // 27 is int and rvalue,

 // so uref3's type is int&&

 

上面遵循case2.

 

不多说了,重点说下区别。

auto会把花括号形式数据,转换为初始化列表。

auto x3 = { 27 }; // type is std::initializer_list<int>,

 // value is { 27 }

 

而这样如下方式使用模板就是错误

template<typename T> // template with parameter

void f(T param); // declaration equivalent to

 // x's declaration

f({ 11, 23, 9 }); // error! can't deduce type for T

 

 

并且对于C++14来说,无法编译器无法推断花括号返回类型,包括函数和lambda。

也无法推断lamda的auto形参类型。

你可能感兴趣的:(effective)