问题
Since auto and decltype are both used to infer the types. I thought they would be same.
However, the answer to this question suggests otherwise.
Still I think they cannot be entirely different.
I can think of a simple example where the type of i will be same in both the following cases.
auto i = 10; and decltype(10) i = 10;
So what are the possible situations where auto and decltype would behave equivalently.
回答1:
auto behaves exactly the same as template argument deduction, meaning if you don't specify a reference to it, you don't get one. decltype is just the type of an expression and as such takes references into account:
#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/equivalence-between-decltype-and-auto