How do I use decltype and decltype(auto) in C++?

In C++, `decltype` and `decltype(auto)` are powerful features that can be used to deduce the type of expressions at compile time. These features are especially useful for templates and can help in writing generic code that is type-safe.

Using decltype

The `decltype` keyword examines the declared type of an expression, allowing you to retrieve its type without evaluating the expression. This can be particularly useful when you want to declare a variable with the type of another expression.

Example of decltype

#include <iostream> int main() { int x = 42; decltype(x) y = 100; // y will have the same type as x (int) std::cout << "Type of y: " << typeid(y).name() << std::endl; // Printing type of y return 0; }

Using decltype(auto)

Introduced in C++14, `decltype(auto)` allows for more flexible type deduction. It deduces the type of an expression while preserving the value category (lvalue/rvalue) of the expression, making it ideal for returning the results of complex expressions in functions.

Example of decltype(auto)

#include <iostream> int getValue() { return 42; } int main() { decltype(auto) value = getValue(); // value will be deduced as int std::cout << "Value: " << value << std::endl; return 0; }

C++ decltype decltype(auto) type deduction C++14 compile time templates