`decltype` — C++ Keyword
`decltype` — C++ Keyword
The decltype keyword in C++: deduces the type of an expression without evaluating it.
`decltype` — C++ Keyword
The decltype keyword in C++: deduces the type of an expression without evaluating it.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
decltypeDeduces the exact type of an expression without evaluating it. Unlike auto, decltype preserves references and const-qualifiers.
decltype(expression) // type of expression
decltype(auto) // deduce return type like decltype (C++14)
#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
}
decltype(e) where e is an lvalue expression (parenthesized) yields a reference type: decltype((x)) is int&.decltypeint 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;
}