因为 auto 和 decltype 都用于推断类型。我想 他们会是一样的。
但是,this 的答案问题表明并非如此。
我仍然认为它们不能完全不同。
我可以想到一个简单的例子,其中 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");
}
关于c++ - decltype 和 auto 之间的等价性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459928/