...

/

Automatic Type Deduction: auto

Automatic Type Deduction: auto

In this lesson, we will discuss the automatic type deduction using auto.

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-value
int i= 5; // explicit
auto i1= 5; // auto
// define a reference to an int
int& b= i; // explicit
auto& b1= i; // auto
// define a pointer to a function
int (*add)(int,int)= myAdd; // explicit
auto add1= myAdd; // auto
// iterate through a vector
std::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 ...