Ch2.12: decltype(auto)

What is decltype(auto)?

The keyword decltype(auto) combines the behavior of auto and decltype. It deduces the type of an expression, but preserves references and const qualifiers like decltype does.

Basic Examples


#include <cstddef>

::std::size_t x{42zu};

auto a{x};            // deduced as ::std::size_t (copy)
decltype(auto) b{x};  // deduced as ::std::size_t& (reference)

auto strips references, while decltype(auto) preserves them.

Return Types

We will introduce functions in detail later. For now, we show decltype(auto) with functions first, because return types are the most common use case.


#include <cstddef>

::std::size_t global{100zu};

auto get_copy() {
    return global; // returns ::std::size_t (copy)
}

decltype(auto) get_ref() {
    return (global); // returns ::std::size_t& (reference)
}

Using decltype(auto) ensures that if you return a reference, the caller receives a reference, not a copy.

⚠️ Beware: Parentheses Matter


#include <cstddef>

::std::size_t y{200zu};

decltype(auto) c{y};   // deduced as ::std::size_t (copy)
decltype(auto) d{(y)}; // deduced as ::std::size_t& (reference)

Just like with decltype, parentheses change the meaning:

Always be mindful of parentheses when using decltype(auto).

Key Takeaways