Trailing Return Type in C++ 11
Last Updated :
06 Sep, 2023
The trailing return type syntax, a new method of indicating a function’s return type, was introduced in C++11.
Before C++11, the return type of a function was typically specified before the function name. However, in some cases, it could be challenging to express complex return types, especially when dealing with template functions or functions with decltype.
With the trailing return type syntax, you can specify the return type of a function after the parameter list using the auto keyword and the trailing -> arrow. This allows you to use expressions and decltype to deduce the return type based on the function’s implementation.
In the older format, it was necessary to specify the return type before the name of the function.
Syntax of Return Type before C++11
function_return_type function_name(parameter_list){
// Function implementation
// ...
}
In the new syntax, auto keyword is written before the function name and the return type is specified after the function name and parameter list.
Syntax of Trailing Return Type
auto function_name(parameter_list) -> return_type {
// Function implementation
// ...
}
Example of Trailing Return Type
C++
#include <iostream>
auto add( int a, int b) -> decltype (a + b) { return a + b; }
int main()
{
int x = 5, y = 10;
auto result = add(x, y);
cout << "Result: " << result
<< endl;
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...