Type inference in C++

In this tutorial, we are going to learn about type inference in C++. Type inference actually means automatic deduction of the type of the variable we are using. In C++, we have methods to detect the type of data automatically. This feature strengthens the use of C++.

Type inference in C++ can be useful for many instances. However, it does increase the compile time as types are deduced while the code is being compiled. The methods of type inference are given below.

auto keyword

We can use the auto keyword in our program to deduce the data type of variable. We can also use it as the return type for a function. In that case, the return type for the function is evaluated at the run time.

See the below code to grasp it well.

#include <bits/stdc++.h> 

using namespace std;

int main()
{
  auto a = 5;
  auto b = 6.0;
  auto c = 7.2f;
  
  cout << "Type of " << a << " is " << typeid(a).name() << "." << endl;
  cout << "Type of " << b << " is " << typeid(b).name() << "." << endl;
  cout << "Type of " << c << " is " << typeid(c).name() << "." << endl;
  
  return 0; 
}


The above program gives the output as:

Type of 5 is i.
Type of 6 is d.
Type of 7.2 is f.

As you can see in the output auto keyword successfully detects the type for a, b and c variables.

A more common use of auto can be seen while creating iterators. See here.

#include <bits/stdc++.h> 
#include <vector>

using namespace std;

int main() 
{
   vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
   for(auto it = vec.begin(); it != vec.end(); it ++) 
   {
      cout << *it << " ";
   }
   return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

decltype keyword

This keyword evaluates an expression and finds out the type of the result obtained. This can also be very useful in type inference. See the below code for a better understanding.

#include <bits/stdc++.h> 

using namespace std;

float fun()
{
  return 5.9;
}

int main() 
{
   int i;
   decltype(9.5) a;
   decltype(i) b;
   decltype(fun()) c;
   
   cout << typeid(a).name() << endl;
   cout << typeid(b).name() << endl;
   cout << typeid(c).name() << endl;
  
   return 0;
}

As you can see, the type of a is d(double) type of b is i(int) and type of c is f(float). We can also use decltype keyword with auto keyword. That will make our code more efficient and useful.

Thank you.

Also read: Keywords in C++

Leave a Reply

Your email address will not be published. Required fields are marked *