【问题标题】:equivalence between decltype and autodecltype 和 auto 等价
【发布时间】:2012-07-12 20:17:08
【问题描述】:

因为 auto 和 decltype 都用于推断类型。我想 他们会是一样的。

但是,this 问题的答案表明并非如此。

我仍然认为它们不可能完全不同。 我可以想到一个简单的例子,i 的类型在以下两种情况下都是相同的。

auto i = 10; and decltype(10) i = 10;

那么 auto 和 decltype 表现相同的可能情况是什么。

【问题讨论】:

  • 您重复了第二个定义中的 10。这还不够不同吗?这是给我的。 auto 在日常生活中方式decltype 更有用,decltype 主要用作元编程工具。
  • 现在,我只关心推断的类型。
  • 它们并不完全不同。你现在喜欢的另一个答案呢?
  • decltype vs auto的可能重复

标签: c++ type-inference auto decltype


【解决方案1】:

auto 的行为完全与模板参数推导相同,这意味着如果你不指定对它的引用,你就不会得到一个。 decltype 只是表达式的类型,因此会考虑引用:

#include <type_traits>

int& get_i(){ static int i = 5; return i; }

int main(){
  auto i1 = get_i(); // copy
  decltype(get_i()) i2 = get_i(); // reference
  static_assert(std::is_same<decltype(i1), int>::value, "wut");
  static_assert(std::is_same<decltype(i2), int&>::value, "huh");
}

Live example on Ideone.

【讨论】:

  • auto 也可以与 decltype 结合使用。 msdn.microsoft.com/en-us/library/dd537655.aspx
  • @0A0D:这只是后期指定的返回类型。
  • 更具体地说,decltype 将其表达式的值类别转换为引用限定:左值被限定为左值引用,xvalue 被限定为右值引用。 get_i() 的类型不是“int&amp;”,而是“int 类型的左值。表达式永远不会有引用类型。
  • @James:的确,我想我会保持简单。
猜你喜欢
  • 1970-01-01
  • 2011-10-15
  • 2017-08-02
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
相关资源
最近更新 更多