A. *_* K. 1 c++ type-inference decltype auto
由于auto和decltype都用于推断类型.我以为他们会一样的.
但是,这个问题的答案表明不然.
我仍然认为他们不可能完全不同.我可以想到一个简单的例子,其中i两种情况下的类型相同.
auto i = 10; and decltype(10) i = 10;
Run Code Online (Sandbox Code Playgroud)
那么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");
}
Run Code Online (Sandbox Code Playgroud)