【问题标题】:Does the C++11 standard guarantee "n2 is int&" by "auto n2 = const_cast<int&>(n);"?C++11 标准是否通过“auto n2 = const_cast<int&>(n);”保证“n2 is int&”?
【发布时间】:2016-12-06 10:29:56
【问题描述】:
const int n = 0;
auto& n1 = const_cast<int&>(n);
auto n2 = const_cast<int&>(n);

C++11 标准是否保证 n2 is int&amp; by auto n2 = const_cast&lt;int&amp;&gt;(n);

我必须使用auto&amp; n1 = const_cast&lt;int&amp;&gt;(n); 而不是auto n2 = const_cast&lt;int&amp;&gt;(n);吗?

根据 C++11 标准,这两种方式是否完全等价?

【问题讨论】:

  • 很确定n2int,没有任何参考。 auto 基本遵循模板实参推演规则。
  • 请注意,使用 C++14 的 decltype(auto),您可以应用 decltype 规则,您将获得 int&amp;

标签: c++ c++11 auto type-systems type-deduction


【解决方案1】:

auto 使用与常规函数模板参数推导相同的规则,从不推导引用。

另一方面,C++14 decltype(auto) 可以在这里推导出一个参考。以及 C++11 auto&amp;&amp;

const int n = 0;
auto a = const_cast<int&>(n);           // a is int
decltype(auto) b = const_cast<int&>(n); // b is int&
auto&& c = const_cast<int&>(n);         // c is int&

【讨论】:

    【解决方案2】:

    auto 本身永远不会产生引用类型。

    所以n2int 类型。

    (如果我每次看到for (auto s : expensive_deep_copy_container) 之类的代码都能得到一美元)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2012-03-24
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      相关资源
      最近更新 更多