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
autokeyword?Auto drops the
constand reference&qualifiers. You must specify them again if you want it.
Both decltype and auto determine things at compile time.
Resources
- https://en.cppreference.com/w/cpp/language/decltype
- https://federico-busato.github.io/Modern-CPP-Programming/htmls/10.Templates_I.html
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 constor 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.
 
- When you need the exact type (including references or 
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/