Advertisement
Advanced C++, Type Deduction & auto

What is decltype(auto) and when is it needed?

Short answer

decltype(auto) (C++14) deduces a type using decltype rules rather than auto rules, so it preserves references and const.

Save C++ mock interview
Advertisement
AModel answer
decltype(auto) (C++14) deduces a type using decltype rules rather than auto rules, so it preserves references and const. It's used mainly for return types of forwarding/wrapper functions that must return exactly what an inner call returns (a reference if the inner returns a reference), which plain auto would incorrectly turn into a value.
template <class F, class... A>
decltype(auto) call(F f, A&&... a) {
    return f(std::forward<A>(a)...); // preserves ref-ness
}
Real-world example
A perfect-forwarding wrapper uses decltype(auto) so it returns a reference when the wrapped function does.
Likely follow-ups
  • How does it differ from auto return? | Why do wrappers need it?
Related topics