decltype(auto)
can deduce a value and a reference. auto
never deduces a reference. It sounds to me for generic code and optimization decltype(auto)
should always be preferred. Is this the case? Consider for example returning an object which may or may not be copyable. auto&
is required to avoid copying it, but that forces it to be a reference always. decltype(auto)
is the correct option in this case. What are the disadvantages of decltype(auto)
aside from being more typing?
From the isocpp C++14 FAQ on decltype(auto)
:
Note: decltype(auto) is primarily useful for deducing the return type of forwarding functions and similar wrappers, as shown above, where you want the type to exactly “track” some expression you’re invoking. However, decltype(auto) is not intended to be a widely used feature beyond that. In particular, although it can be used to declare local variables, doing that is probably just an antipattern since a local variable’s reference-ness should not depend on the initialization expression. Also, it is sensitive to how you write the return statement. These two functions have different return types.
look_up_a_string_1
returns astring
whilelook_up_a_string_2
returns astring&
.
decltype(auto) look_up_a_string_1() { auto str = lookup1(); return str; }
decltype(auto) look_up_a_string_2() { auto str = lookup1(); return(str); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With