Type deduction, also called as type inference, is a feature used by compiler to determining object types from the object’s initializer.
We can use auto keyword while defining and initializing a variable where we want compiler to deduce the type.
auto variable {1}; // deduces integer from the initializer value.The initializer value can be a function and compiler would infer the type from function return type.
It is important to provide some value from where type can be inferred. If we provide empty initializer or just definition, compiler would have no way to infer type.
auto b; // invalid
auto a {}; //invalid
auto c {void_function()}; // invalidAdvantages of Type Deductions
- If you have habit of just defining variable without initializing them, compiler will throw error when using
autoas shown below.
int b; // no complain
auto a; // complain.- There will not be any type conversion and so no unintended performance issue that may happen because of those conversions. For example,
// getValue function returns string view.
std::string_view value{getValue()};
std::string value{getValue()}; // bad: maybe unintensional to convert to string view to string.
auto value{getValue()}; // good: no conversion.Problems with Type Deductions
With some advantages, there some couple of downsides with type deductions.
- Type deductions remove the explicit mention of type which obstructs having object’s type information in the code. For example, using
autowill make the code does not having object’s type information which would have been there otherwise. - If the initializer value changes, the variable type changes. For example,
auto value {getValue() + 5};If getValue return type changes, type of value changes, which may not be desired.