
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Type Inference in C++
Type inference (or, type deduction) refers to the automatic detection of the data type of an expression in a programming language. In C++, the auto keyword is used for automatic type deduction.
For example, you want to create an iterator to iterate over a vector, you can simply use auto for that purpose.
It is helpful, when dealing with complicated STL containers, iterators, and lambda functions where it may be hard to write the full type.
This can be achieved using auto, decltype, and decltype(auto) keywords. These approaches help in letting the compiler understand the correct data types without explicitly declaring them.
Using auto Keyword
The auto keyword is used to figure out the variable's type based on the value you have been assigned to it.
Example
Here, we initialize the variables using 'auto' and creates a vector of integers through loops to print each value.
#include <iostream> #include <vector> using namespace std; int main() { auto x = 10; // int auto y = 3.14; // double auto str = "Hello World"; // const char* vector<int> v = {1, 2, 3, 4}; for (auto val : v) { cout << val << " "; } return 0; }
Output
The above program produces the following result:
1 2 3 4
Using decltype Keyword
The decltype keyword is used to get the type of a variable or expression without specifying manually .
Example
In this example, we declare an integer 'a' by using decltype(a) to ensure b has the same type as a.
.#include <iostream> using namespace std; int main() { int a = 42; decltype(a) b = a + 8; // b has type int, same as a cout << "b = " << b << endl; return 0; }
Output
The above program produces the following result:
b = 50
Using decltype(auto) Keyword
The decltype(auto) keyword is used to understand both the type and value category (like lvalue or rvalue) of an expression.
Example
In this example, we return a reference to x using decltype(auto), and assign it to ref to modifies x through ref.
#include <iostream> using namespace std; int x = 100; decltype(auto) getX() { return (x); // returns int& } int main() { decltype(auto) ref = getX(); ref = 200; cout << "x = " << x << endl; return 0; }
Output
The above program produces the following result:
x = 200