What is decltype and how does it differ from auto?
Short answer
decltype(expr) yields the declared type of an expression without evaluating it, preserving references and const exactly (unlike auto, which strips them for value deduction).
Advertisement
AModel answer
decltype(expr) yields the declared type of an expression without evaluating it, preserving references and const exactly (unlike auto, which strips them for value deduction). It's used to declare variables or return types that must match an expression's type precisely, especially in templates and trailing return types.
int x = 0; int& r = x;
auto a = r; // int (copy)
decltype(r) b = x; // int& (reference preserved)Real-world example
decltype captures the exact type of a container element to declare a matching variable in generic code.
Likely follow-ups
- Does decltype evaluate its argument? | Why does it preserve references?
Related topics