Type Inference | C++

/Type Inference | C++

Type Inference refers to automatic deduction of the data type of an expression in a programming language. Before C++ 11, each data type needs to be explicitly declared at compile time, limiting the values of an expression at runtime but after the new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself.
With type inference capabilities, we can spend less time having to write out things compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the run time of the program.

 

auto keyword

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime. A good use of auto is to avoid long initializations when creating iterators for containers.

// use auto to save time when creating iterators 
using namespace std; 

// Return type is the type of operator+(T, U)
template<class T, class U>
auto add(T t, U u) { return t + u; } 

int main() 
{ 
  // Create a set of strings 
  set<string> st; 
  st.insert({"UK", "USA", "IND"}); 

  // 'it' evaluates to iterator to set of string type automatically 
  for (auto it = st.begin(); it != st.end(); it++) 
    cout << *it << " "; 

  auto a = 1 + 2;            // type of a is int
  auto b = add(1, 1.2);      // type of b is double
  auto d = {1, 2}; // OK: type of d is std::initializer_list<int>
  return 0; 
}

If the placeholder type specifier is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0; is ill-formed, while the declaration auto i = 0, *p = &i; is well-formed and the auto is deduced as int.

 

decltype Keyword

It inspects the declared type of an entity or the type of an expression. Auto lets you declare a variable with particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression.

// Use of decltype 
char fun() { return 'g'; } 

int main() 
{   
  // Type of y is same as return type of fun() 
  decltype(fun()) y; 
  
  int x = 5; 
  // j will be of type int : data type of x 
  decltype(x) j = x + 5; 

  return 0; 
}

 

 

September 11th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of