template boy template boy - 8 months ago 46
C++ Question

What is the difference between auto and decltype(auto) when returning from a function?

I rarely see

but when I do it confuses me because it seems to do the same thing as
when returning from a function.

auto g() { return expr; }
decltype(auto) g() { return expr; }

What is the difference between these two syntaxes?


auto follows the template argument deduction rules and is always an object type; decltype(auto) follows the decltype rules for deducing reference types based on value categories. So if we have

int x;
int && f();


expression    auto       delctype(auto)
10            int        int
x             int        int
(x)           int        int &
f()           int        int &&