01类型推导 Scott Meyers的effective modern c++讲座摘要

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

decltype(declared type)的类型推导:

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

函数返回类型的推导:

auto foo() // 按照模板方式来推导
decltype(auto) foo // 按照decltype方式来推导

但是创建函数时到底怎么用呢?简单地说,不需要修改内部数据,则使用auto, 否则使用decltype(auto)

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

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

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

posted @ 2019-03-27 13:33  hanjackcyw  阅读(378)  评论(0编辑  收藏  举报