C++ decltype与auto的等价性

C++ decltype与auto的等价性,c++,type-inference,auto,decltype,C++,Type Inference,Auto,Decltype,因为auto和decltype都用于推断类型。我想 他们会是一样的 然而,对这个问题的回答却表明了相反的观点 但我认为它们不能完全不同。 我可以想出一个简单的例子,在以下两种情况下,I的类型是相同的 auto i = 10; and decltype(10) i = 10; 那么,在什么情况下,auto和decltype的行为可能是等价的。auto的行为与模板参数推断完全相同,这意味着如果不指定对它的引用,就不会得到引用decltype只是表达式的类型,因此会考虑引用: #include &l

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

然而,对这个问题的回答却表明了相反的观点

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

auto i = 10; and decltype(10) i = 10;
那么,在什么情况下,auto和decltype的行为可能是等价的。

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");
}
#包括
int&get_i(){static int i=5;return i;}
int main(){
auto i1=get_i();//复制
decltype(get_i())i2=get_i();//引用
静态断言(std::is_same::value,“wut”);
静态断言(std::is_same::value,“huh”);
}

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");
}
#包括
int&get_i(){static int i=5;return i;}
int main(){
auto i1=get_i();//复制
decltype(get_i())i2=get_i();//引用
静态断言(std::is_same::value,“wut”);
静态断言(std::is_same::value,“huh”);
}

您正在重复第二个定义中的10。这还不够吗?是给我的
auto
在日常生活中比decltype更有用,decltype主要用作元编程工具。目前,我只关心推断类型。它们并没有完全不同。你现在喜欢的另一个答案呢?可能是重复第二个定义中的10。这还不够吗?是给我的
auto
在日常生活中比decltype更有用,decltype主要用作元编程工具。目前,我只关心推断类型。它们并没有完全不同。你现在喜欢的另一个答案呢?可能的auto副本也可以与decltype一起使用@0A0D:这只是后期指定的返回类型。更具体地说,
decltype
将其表达式的值类别转换为引用限定:左值限定为左值引用,xvalue限定为右值引用。
get_i()
的类型不是“
int&
”,而是“类型为
int
的左值。表达式从来没有引用类型。@James:的确,我想我应该保持它的简单,不过.auto也可以与decltype结合使用@0A0D:这只是后期指定的返回类型。更具体地说,
decltype
将其表达式的值类别转换为引用限定:左值限定为左值引用,xvalue限定为右值引用。
get_i()
的类型不是“
int&
”,而是“一个
int
类型的左值。表达式从来没有引用类型。@James:的确,我想我还是简单一点吧。