C++ decltype | Extract Expression Types

C++ decltype | Extract Expression Types

이 글의 핵심

How decltype preserves references and const, how it pairs with auto and C++14 decltype(auto), and common template patterns.

What is decltype?

decltype yields the type of an expression. Unlike plain auto in many cases, it can preserve top-level const and reference.

int x = 10;
decltype(x) y = 20;        // int

const int& ref = x;
decltype(ref) z = x;       // const int&

auto vs decltype

const int& r = x;
auto a = r;           // int (decay)
decltype(r) b = r;    // const int&

Trailing return types (C++11)

template<typename T, typename U>
auto add(T a, U b) -> decltype(a + b) {
    return a + b;
}

decltype(auto) (C++14)

int& getRef();

auto a = getRef();            // int
decltype(auto) b = getRef();  // int&

Note: decltype(auto) applies decltype rules to the initializer—it does not “always add references.”

SFINAE

template<typename T>
auto process(T v) -> decltype(v.size(), void()) {
    // selected only if v.size() is valid
}

Use with std::declval, void_t, or C++20 requires for structured constraints.

decltype vs decltype(( ))

int x = 10;
decltype(x)   // int
decltype((x)) // int&  — lvalue expression

  • auto keyword
  • SFINAE

Keywords

C++, decltype, decltype(auto), trailing return type, templates