Summary of objective Modern C ++ Item 2, inclutivemodernc
First, we propose two basic points of view:
1. auto and template parameter type derivation have almost identical rules, so the rules summarized in Item1 are applicable to auto.
2. There is a difference between auto and template parameter type derivation. The difference is that the process for curly braces is different. Why is it different? Rule! Scotter Meyer does not know the answer.
We know Item1 and propose three different cases:
1. The type descriptor is a pointer or reference, and is not a global reference.
2. the type descriptor is a global reference.
3. the type descriptor is neither a pointer nor a reference
template<typename T> void f(ParamType param);
In short, we can regard auto as T in the parameter descriptor of the template function.
const int x=5;auto y=x; //y is int.auto yy= 5; //yy is int.const auto cy = yy;
The above code type derivation follows case3, and all auto types are int.
const auto& ry= yy;
The above Code follows 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.
Let's talk about the difference.
Auto converts curly brackets to the initialization list.
auto x3 = { 27 }; // type is std::initializer_list<int>, // value is { 27 }
Using the template as follows is incorrect.
template<typename T> // template with parametervoid f(T param); // declaration equivalent to // x's declarationf({ 11, 23, 9 }); // error! can't deduce type for T
In addition, for C ++ 14, the compiler cannot infer the type returned by curly braces, including functions and lambda.
The auto parameter type of lamda cannot be inferred.