【问题标题】:The ref- and cv-stripping property of `auto`.`auto` 的 ref- 和 cv-stripping 属性。
【发布时间】:2013-06-24 10:17:23
【问题描述】:

我了解到以这种方式使用 auto 声明变量

auto var = expr;

基本上就像采用 expr 的类型并从中剥离 &/&&-references 以及所有顶级常量和易失性。这是否意味着上面的行完全等同于下面的?

std::remove_cv<std::remove_ref<decltype(expr)>::type>::type var = expr;

【问题讨论】:

  • 你可能会喜欢 C++14 中即将推出的 decltype(auto) :-)
  • @KerrekSB 你能提供更多细节吗?
  • 这是auto的类型推导结合decltype的引用语义——如decltype(auto) x = foo();

标签: c++ c++11 auto decltype


【解决方案1】:

不,那不是真的。 auto var = expr; 更像是按值传递 expr

int x[1];
auto y = x;

这使得y 成为int*

大部分auto x = expr;的行为类似于模板类型推导:

template <typename T>
void f(T);
int x[1];
f(x); // deduces T as int*

更像std::decay&lt;decltype(expr)&gt; var = expr;

【讨论】:

  • 那么std::decay&lt;decltype(expr)&gt;::type var = expr; 究竟 是否等同于auto var = expr
  • 不完全是。这就是 C++:它的规则是唯一没有例外的规则就是这条规则。 auto x = []{}; 是 lambda 类型,但是 lambdas 不能在 decltype 中使用。
猜你喜欢
  • 2013-03-16
  • 2022-12-02
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 2023-03-06
  • 2012-04-05
  • 1970-01-01
相关资源
最近更新 更多