decltype (C++)

decltype is a keyword in C++ that determines the type of an expression at compile-time without evaluating the expression itself.

How is this different from auto keyword?

Auto drops the const and reference & qualifiers. You must specify them again if you want it.

Both decltype and auto determine things at compile time.

Resources

const int a = 5;
auto x = a;    // int (drops const)
 
const int a = 5;
decltype(a) y = a;   // const int (preserves const)
  • Use auto:
    • When the initializer clearly shows the intended type.
    • For cleaner and more concise code.
    • When you don’t need to preserve const or reference qualifiers.
  • Use decltype:
    • When you need the exact type (including references or const).
    • For templates and advanced metaprogramming.
    • When deducing types from complex expressions or function return values.

Example?

#include <iostream>
#include <type_traits>
 
template<typename T>
void checkType() {
    typename std::remove_const<T>::type value; // Removes const qualifier
    std::cout << "Is const: " << std::is_const<decltype(value)>::value << "\n";
}
 
int main() {
    checkType<const int>(); // Output: Is const: 0 (false)
}

https://www.geeksforgeeks.org/type-inference-in-c-auto-and-decltype/