`decltype` — C++ Keyword

`decltype` — C++ Keyword

The decltype keyword in C++: deduces the type of an expression without evaluating it.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

decltype

Deduces the exact type of an expression without evaluating it. Unlike auto, decltype preserves references and const-qualifiers.

Syntax

decltype(expression)   // type of expression
decltype(auto)         // deduce return type like decltype (C++14)

Example

#include <print>
#include <vector>
#include <type_traits>

int compute() { return 42; }

int main() {
    int x = 5;
    decltype(x) y = 10;          // y is int
    decltype(x + 1.0) z = 1.0;  // z is double

    std::vector<int> v = {1, 2, 3};
    decltype(v[0]) first = v[0]; // int& (subscript returns reference)

    // decltype(auto) in function returning reference
    auto& get = [&]() -> decltype(auto) { return v[0]; };
    get() = 99;
    std::println("{}", v[0]);  // 99

    // In trailing return type
    auto add = [](auto a, auto b) -> decltype(a + b) { return a + b; };
    std::println("{}", add(1, 2));       // 3
    std::println("{:.1f}", add(1.5, 2.5)); // 4.0
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}