auto 类型推导与模板类型推导相同,除了一种情况
auto x1 = 27; // 类型int
auto x2(27); // 类型int
auto x3 = {27}; // 类型std::initializer_list<int>
auto x4{27}; // 类型std::initializer_list<int>如果对模板传入一个同样的初始化表达式,类型推导就会失败:
auto x = {11, 23, 9};
// std::initializer_list<int>
template <typename T>
void f(T param);
f({11, 23, 9});
// 无法推导不过,如果使用如下语句可以通过编译:
template <typename T>
void f(std::initializer_list<T> initList);
f({11, 23, 9}); // std::initializer_list<int>在C++14中,带有auto返回值的函数若要返回一个初始化表达式,无法通过编译:
auto createInitList() {
return {1, 2, 3}; // error
}lambda表达式形参类型为auto时,也不允许使用初始化表达式:
std::vector<int> v;
...
auto resetV =
[&v](const auto& newValue) { v = newValue; };
...
resetV({1, 2, 3}); // error