decltype vs auto

James Leonard picture James Leonard · Aug 23, 2012 · Viewed 16.2k times · Source

As I understand it, both decltype and auto will attempt to figure out what the type of something is.

If we define:

int foo () {
    return 34;
}

Then both declarations are legal:

auto x = foo();
cout << x << endl;

decltype(foo()) y = 13;
cout << y << endl;

Could you please tell me what the main difference between decltype and auto is?

Answer

Mankarse picture Mankarse · Aug 23, 2012

decltype gives the declared type of the expression that is passed to it. auto does the same thing as template type deduction. So, for example, if you have a function that returns a reference, auto will still be a value (you need auto& to get a reference), but decltype will be exactly the type of the return value.

#include <iostream>
int global{};
int& foo()
{
   return global;
}

int main()
{
    decltype(foo()) a = foo(); //a is an `int&`
    auto b = foo(); //b is an `int`
    b = 2;

    std::cout << "a: " << a << '\n'; //prints "a: 0"
    std::cout << "b: " << b << '\n'; //prints "b: 2"

    std::cout << "---\n";
    decltype(foo()) c = foo(); //c is an `int&`
    c = 10;

    std::cout << "a: " << a << '\n'; //prints "a: 10"
    std::cout << "b: " << b << '\n'; //prints "b: 2"
    std::cout << "c: " << c << '\n'; //prints "c: 10"
 }

Also see David Rodríguez's answer about the places in which only one of auto or decltype are possible.