Type Inference in C++ (auto and decltype)

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to understand Type interference in C++ (auto and decltype).

In case of auto keyword, the type of the variable is defined from the type of its initializer. Further with decltype, it lets you extract the type of variable from the called element.

auto type

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   auto x = 4;
   auto y = 3.37;
   auto ptr = &x;
   cout << typeid(x).name() << endl
      << typeid(y).name() << endl
      << typeid(ptr).name() << endl;
   return 0;
}

Output

i
d
Pi

decl type

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int fun1() { return 10; }
char fun2() { return 'g'; }
int main(){
   decltype(fun1()) x;
   decltype(fun2()) y;
   cout << typeid(x).name() << endl;
   cout << typeid(y).name() << endl;
   return 0;
}

Output

i
c
raja
Published on 12-Mar-2020 06:23:44
Advertisements