Automatic Type Deduction: auto
In this lesson, we will discuss the automatic type deduction using auto.
We'll cover the following...
The Facts of auto
Automatic type deduction with auto
is extremely convenient. Firstly, we save unnecessary typing, in particular with challenging template expressions. Secondly, the compiler does not make human errors.
The compiler automatically deduces the type from the initializer:
auto myDoub = 3.14;
Key Features
- The techniques for automatic function template argument deductions are used.
- It is very helpful in complicated template expressions.
- It empowers us to work with unknown types.
- It must be used with care in combination with initializer lists.
The following code compares the definition of explicit and deduced types:
Press + to interact
#include <vector>int myAdd(int a,int b){ return a+b; }int main(){// define an int-valueint i= 5; // explicitauto i1= 5; // auto// define a reference to an intint& b= i; // explicitauto& b1= i; // auto// define a pointer to a functionint (*add)(int,int)= myAdd; // explicitauto add1= myAdd; // auto// iterate through a vectorstd::vector<int> vec;for (std::vector<int>::iterator it= vec.begin(); it != vec.end(); ++it){}for (auto it1= vec.begin(); it1 != vec.end(); ++it1) {}}
C++ Insights helps us to visualize of the types that the compiler deduces. Andreas Fertig, author of this tool, wrote a few [blog] enteries (https://www.modernescpp.com/index.php/c-insights-typ ...