Learn How To Use Return Type Deduction In C++ For Windows Apps
In this tutorial, you will learn how to use return type deduction in C++ Builder. For the C++14 scheme of auto with functions, the compiler can deduce return types for any function, no matter how complex it is. The only requirement is that each return statement needs have the same type. The practices are identical as for auto variables.
To deduce the type, the compiler requires to detect the function definition right ahead. That means this technique is limited to function templates, inline functions, and helper functions which are applied only inside a particular translation unit.
Here is a code example on return type deduction
#include
#include
class employee {
// Lots of code here
};
struct person_id {
std::string first_name;
std::string last_name;
};
class employees {
public:
auto find_employee(const std::string& name) { return 1; }
};
int return_an_int() {
return 1;
}
auto return_something() {
return 1;
}
// The following will give a compiler error, because int and
// float are different types
//auto returnConfusion() {
// if (std::rand() %2 == 0) {
// return -1;
// } else {
// return 3.14159;
// }
//}
int main() {
auto i{ return_an_int() };
auto j{ return_something() };
// Example of a method with multiple return points, each with different types – an error
// auto k {returnConfusion()};
auto employee_list{ std::make_unique
auto person = employee_list->find_employee(“Jane Smith”);
system(“pause”);
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
#ifdef _WIN32 #include #else typedef char _TCHAR; #define _tmain main #endif
#include #include
class employee { // Lots of code here };
struct person_id { std::string first_name; std::string last_name; };
class employees { public: auto find_employee(const std::string& name) { return 1; } };
int return_an_int() { return 1; }
auto return_something() { return 1; }
// The following will give a compiler error, because int and // float are different types //auto returnConfusion() { // if (std::rand() %2 == 0) { // return -1; // } else { // return 3.14159; // } //} int main() { auto i{ return_an_int() };
auto j{ return_something() };
// Example of a method with multiple return points, each with different types – an error // auto k {returnConfusion()};
auto employee_list{ std::make_uniqueemployees>() };
auto person = employee_list->find_employee(“Jane Smith”);
system(“pause”); return 0; } |
So, return type deduction bypasses undesirable conversions and the removes type changes you must to apply.
If there is a possibility to use return type deduction, just apply this technique. Because this can assist to secure the types you utilize more consistently.