Search code examples
c++type-inferenceautodecltype

What is the difference between decltype and auto as a placeholder type for variables?


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;
decltype(auto)  y = 13; // alternatively, since C++14
cout << y << endl;

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


Solution

  • 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&`
     // decltype(auto)  a = foo();   alternatively, since C++14
    
        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&`
     // decltype(auto)  c = foo();   alternatively, since C++14
        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.