equivalence between decltype and auto

一曲冷凌霜 提交于 2019-12-24 09:15:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!