正文
1.普通情形
在c++11中,引入了auto
关键字,关于auto
关键字的推导,绝大多数和上一个Item的模板推导是一样的。例如:
auto x = 27; // case 3 (x is not reference)
const auto cx = x; // case 3 (cx isn't either)
const auto& rx = x; // case 1 (rx is a non-universal ref.)
上面的三个例子结果都是int
,对于case 2(即universal引用)我们有如下的例子:
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&&
对于数组和函数指针的情况,auto
也有类似的表现:
const char name[] = // name's type is const char[13]
"R. N. Briggs";
auto arr1 = name; // arr1's type is const char*
auto& arr2 = name; // arr2's type is const char (&)[13]
void someFunc(int, double); // someFunc is a function;
// type is void(int, double)
auto func1 = someFunc; // func1's type is void (*)(int, double)b
auto& func2 = someFunc; // func2's type is void (&)(int, double)
2.推导initializer_list
由此可见,大部分情况,auto
和模板的类型推导是一样的。但是有如下一个例外:C++11中引入了initializer_list这个新特性,方便了用户初始化container等结构化数据。但是auto
和模板在这个方面的支持并不一样。我们先看一个简单的例子:
auto x1 = 27; // type is int, value is 27
auto x2(27); // ditto
auto x3{ 27 }; // ditto
auto x4 = { 27 }; // type is std::initializer_list<int>, value is { 27 }
这里由于新的标准N3922,和原书中的解释有所不同:原书中x3
和x4
类型一样,但在新的标准下x3
也被推断为int
。
但是模板类型的推导却没有这么只能,考虑如下的例子:
auto x = { 11, 23, 9 }; // x's type is std::initializer_list<int>
template<typename T>
void f(T param);
f({ 11, 23, 9 }); // error! can't deduce type for T
template<typename T>
void f(std::initializer_list<T> initList);
f({ 11, 23, 9 }); // T deduced as int, and initList's
// type is std::initializer_list<int>
你可以看到模板并不会自动推导成std::initializer_list
,但是auto
会这样。所以你需要注意的是在声明变量时不要因为花括号错误地声明了std::initializer_list
(而不是你想要的类型)。
这些便是C++11中的全部内容。但在C++14中,我们有了新的东西:
auto
被允许作为函数返回类型auto
被允许成为lambda表达式中的参数类型
但是这两种情况auto
都只能做蕾丝模板类型推导而不是刚刚提到的auto
特有的类型推导。因此下面两种关于std::initializer_list
的情况无法通过编译的:
auto createInitList() {
return { 1, 2, 3 }; // error: can't deduce type for { 1, 2, 3 }
}
std::vector<int> v;
...
auto resetV =
[&v](const auto& newValue) { v = newValue; }; // C++14
...
resetV({ 1, 2, 3 }); // error! can't deduce type for { 1, 2, 3 }
总结
本条目的tips:
auto
的类型推导通常和模板类型推导一样。但在关于std::initializer_list
推导时略有不同:auto
会把一些花括号初始化推断成std::initializer_list
,而模板类型不会。auto
在函数返回值或者lambda参数里面应用模板类型推导规则,而不是auto
规则。