In c++14 the decltype(auto)
idiom is introduced.
Typically its use is to allow auto
declarations to use the decltype
rules on the given expression.
Searching for examples of "good" usage of the idiom I can only think of things like the following (by Scott Meyers), namely for a function's return type deduction:
template<typename ContainerType, typename IndexType> // C++14
decltype(auto) grab(ContainerType&& container, IndexType&& index)
{
authenticateUser();
return std::forward<ContainerType>(container)[std::forward<IndexType>(index)];
}
Are there any other examples where this new language feature is useful?
Return type forwarding in generic code
For non-generic code, like the initial example you gave, you can manually select to get a reference as a return type:
but in generic code you want to be able to perfectly forward a return type without knowing whether you are dealing with a reference or a value.
decltype(auto)
gives you that ability:Delaying return type deduction in recursive templates
In this Q&A a few days ago, an infinite recursion during template instantiation was encountered when the return type of the template was specified as
decltype(iter(Int<i-1>{}))
instead ofdecltype(auto)
.decltype(auto)
is used here to delay the return type deduction after the dust of template instantiation has settled.Other uses
You can also use
decltype(auto)
in other contexts, e.g. the draft Standard N3936 also states7.1.6.4 auto specifier [dcl.spec.auto]
The draft also contains this example of variable initialization: