因为auto和decltype都用于推断类型。我以为它们是一样的。
然而,this问题的答案表明并非如此。
不过,我认为它们不可能完全不同。我可以想出一个简单的例子,其中i的类型在以下两种情况下都是相同的。
auto i = 10; and decltype(10) i = 10;那么,在哪些可能的情况下,auto和decltype的行为是相同的呢?
发布于 2012-07-13 04:21:13
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.
https://stackoverflow.com/questions/11459928
复制相似问题