Return type deduction in C++14 with Examples
Last Updated :
28 Jan, 2021
In this article, we will discuss Return Type Deduction in C++14. Using an auto return type in C++14, the compiler will attempt to deduce the return type automatically.
Program 1:
C++14
#include <iostream>
using namespace std;
auto multiply( int a, int b)
{
return a * b;
}
int main()
{
int a = 4, b = 5;
cout << multiply(a, b);
return 0;
}
|
Explanation: In the above program, the multiply(int a, int b) function the compiler will perform the multiplication. As the passed parameters 4 and 5, the compiler will return 20 and since its data type is an integer, the compiler will deduce the type as integer automatically and will return 20 as an integer.
Program 2:
C++14
#include <iostream>
using namespace std;
auto increase( int & a)
{
a++;
return a;
}
int main()
{
int b = 10;
int & c = increase(b);
cout << b << c;
return 0;
}
|
Output:
Explanation: As it can be seen that in the above program compiler is showing an error. This is because in the function increase(int &a), the compiler will return 11 and since its type is an integer, the compiler will deduce its type as integer and return it, but in main, we are assigning an integer value to an integer reference variable c, that’s why it was showing error.
Now, the above problem can be fixed in two ways:
using auto&:
C++14
#include <iostream>
using namespace std;
auto & increase( int & a)
{
a++;
return a;
}
int main()
{
int b = 10;
int & c = increase(b);
cout << b << '\n'
<< c;
return 0;
}
|
using decltype(auto):
C++14
#include <iostream>
using namespace std;
decltype ( auto ) increase( int & a)
{
a++;
return a;
}
int main()
{
int b = 10;
int & c = increase(b);
cout << b << '\n'
<< c;
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...