Auto-type Deduction Rules
Auto-type deduction allows the compiler to deduce the type of a variable from its initializer.
Source code on C++ insights
1. Deduction with reference
If the initializer is a reference, the reference type is stripped, and auto
deduces the underlying type. If you want auto
to deduce a reference, you must explicitly use auto&
.
1 | int a1 = 3; |
2. Deduction with const
If the initializer is const
, auto deduces the type without const
unless explicitly specified.
1 | const int a2 = 3; |
In C++, const
can appear in different context, and its role can be categorized as either top-level const or low-level const.
Top-level const applies to the object itself, indicating that the object itself cannot be modified.
1 | const int x = 42; // `x` is a `const int` (the value of `x` cannot be modified) |
Low-level const applies to the type being referred to or pointed to. It means the value being referred to or pointed to cannot be modified.
1 | const int* ptr = &x; // `ptr` is a pointer to a `const int` (the value of the pointee cannot be modified) |
It is important to note that:
Top-level const is ignored when using auto-type deduction unless explicitly specified. Low-level const is preserved during auto-type deduction.
1 | const int a2 = 3; |
3. Deduction with pointers
If a pointer is involved, auto
deduces the pointer type.
1 | int a3 = 3; |
4. Deduction with Arrays
For arrays, auto
deduces to a pointer to the first element of the array. auto&
deduces the array type.
1 | int arr4[] = {1, 2, 3, 4}; |
5. Deduction with Functions
For functions, auto
deduces to a function pointer.
1 | int f5(int a) {return a;} |
6. Deduction with auto&&
auto&&
deduces a reference type.
- If the initializer is an lvalue, auto&& deduces an lvalue reference.
- If the initializer is an rvalue, auto&& deduces an rvalue reference.
1 | int a6 = 3; |
7. Deduction with Lambda
auto
can be used to deduce the return type of a lambda.
1 | int a7 = 3; |
8. Deduction with decltype(auto)
decltype(auto)
is used when you want the deduced type to match the initializer’s type exactly, including references.
1 | int a8 = 42; |
9. Deduction with auto*
auto*
is deduced as a pointer type.
1 | int a9 = 3; |
Auto-type Deduction Rules
http://chuzcjoe.github.io/2025/01/17/cpp-auto-type-deduction-rules/