Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++14

People also ask

What is the difference between auto and decltype Auto?

auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it.

What is decltype used for?

In the C++ programming language, decltype is a keyword used to query the type of an expression. Introduced in C++11, its primary intended use is in generic programming, where it is often difficult, or even impossible, to express types that depend on template parameters.


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();

then

expression    auto       decltype(auto)
----------------------------------------
10            int        int
x             int        int
(x)           int        int &
f()           int        int &&

auto returns what value-type would be deduced of you assigned the return clause to an auto variable. decltype(auto) returns what type you would get if you wrapped the return clause in decltype.

auto returns by value, decltype maybe not.