《Effective Modern C++》Item 2: Understand auto type deduction.

正文

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,和原书中的解释有所不同:原书中x3x4类型一样,但在新的标准下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:

  1. auto的类型推导通常和模板类型推导一样。但在关于std::initializer_list推导时略有不同:auto会把一些花括号初始化推断成std::initializer_list,而模板类型不会。
  2. auto在函数返回值或者lambda参数里面应用模板类型推导规则,而不是auto规则。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值