类型推导 Scott Meyers的视频摘要

Scott Meyers - Effective Modern C++ part 1
https://www.youtube.com/watch?v=fhM24zs1MFA

decltype(declared type)的类型推导:

  1. 不会忽略const/volatile/reference。
  2. decltype(左值表达式) => T&, 但是如果是decltype(名字) => T, 名字优先,如:
    int x
    decltype(x) => T // x是左值表达式,但是名字优先
    decltype((x)) => T& // (x)也是左值表达式,但不是名字

函数返回类型的推导:
auto foo() // 按照模板方式来推导
decltype(auto) foo // 按照decltype方式来推导
创建函数时具体使用方法,比方说:

auto lookupValue(context info)
{
int index = 通过info计算出index;
return myIntVector[index];
}
上面这个函数通过info查找vecotr 中的一个值,使用auto返回的就是int,不需要修改vector中的内容,lookupValue(info) = 0就不允许。

decltype(auto) authorizeAndIndex(vecotr & v, int index),
{
authorizeUser();
return v[index];
}
上面这个函数在访问数据之前先验证用户,这时返回的就是int&, 可以处理vector中的内容,authorizeAndIdnex(v, 0) = 0这样写是允许的。

最后, decltype(auto)返回类型与函数的实现有关,如果返回的是名字,则返回T, 如果返回的是表达式,则返回T&。

猜你喜欢

转载自www.cnblogs.com/ht1947/p/10606892.html