C++ Reference ยท Keywords and Statements
The decltype specifier
Reference for C++ decltype: querying the declared type of a name or the type and value category of an expression, decltype(auto), trailing return types and pitfalls.
decltype(e) is a type specifier that yields the type of an entity or expression without evaluating it. It exists because auto throws away references and const, and because sometimes you need a type that depends on other types, such as the result of adding two template arguments.
It has two modes. If e is a plain name (an unparenthesized id-expression or member access), you get the type the name was declared with. For any other expression you get its type adjusted by value category: an lvalue of type T becomes T&, an xvalue becomes T&&, a prvalue stays T.
int x = 0; decltype(x) a = 1; // int decltype((x)) b = x; // int& (parenthesized: an lvalue expression) decltype(x + 1.5) c; // double
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
decltype(entity) // declared type of a name or class member access decltype(expression) // type + value category: T&, T&&, or T decltype(auto) // placeholder: deduce with decltype rules (C++14)
| Operand | Result |
|---|---|
Unparenthesized name x |
The declared type of x |
lvalue expression of type T (including (x), *p, a[i]) |
T& |
xvalue (std::move(x), static_cast<T&&>(x)) |
T&& |
prvalue (x + 1, f() returning by value) |
T |
Usage notes
- The operand is an unevaluated operand:
decltype(f())does not callf, anddecltype(*p)is fine even ifpis null. - The parentheses rule is the classic trap:
decltype(x)isintbutdecltype((x))isint&. This matters withdecltype(auto):return (x);returns a reference to a local, which dangles. decltype(auto)is for forwarding wrappers and returns where you must keep references. For ordinary variables,autois clearer.- Trailing return types (
auto f(...) -> decltype(...)) were the C++11 way to name a result type that depends on parameters. Since C++14, a plainautoreturn often suffices. - Combine with
std::remove_reference_t,std::decay_tandstd::remove_cvref_t(C++20) to strip what you do not want. decltypeof a function name gives the function type, e.g.int(int), not a pointer.- Use it in
static_assert(std::is_same_v<...>)as a cheap test of what the compiler deduced. decltype(x) y = x;repeats the type includingconstand references, so a reference variable declared this way must be initialized.
Related
- auto
- Type traits
- Value categories
- Tutorial: auto, Type traits