1

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.

Community
  • 1
  • 1
A. K.
  • 34,395
  • 15
  • 52
  • 89

1 Answers1

7

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.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • 1
    auto can be used in conjunction with decltype too. http://msdn.microsoft.com/en-us/library/dd537655.aspx –  Jul 12 '12 at 20:22
  • 1
    @0A0D: That's just the late-specified return type. – Xeo Jul 12 '12 at 20:24
  • 7
    More specifically, `decltype` converts the value category of its expression into a reference qualification: an lvalue is qualified as an lvalue reference and an xvalue is qualified as an rvalue reference. The type of `get_i()` is not "`int&`," it is "an lvalue of type `int`. An expression never has reference type. – James McNellis Jul 12 '12 at 20:24
  • 1
    @James: Indeed, thought I'd keep it simple, though. – Xeo Jul 12 '12 at 20:25