Return type deduction
By the time we reached C++14, the C++ language started to get smarter and began to care about its users (you, the programmer). Haha.
When it can infer the return type without ambiguity, it does its best to help you!
Take a look at the code
A function can be written like this, with the return
type directly written as auto
.
1
2
3
4
5
6
7
8
auto add(int a, int b) {
return a + b;
}
auto multiply(double a, double b) {
return a * b;
}
Templates can also be written this way, with the return type directly written as auto
.
1
2
3
4
5
6
7
8
template<typename T>
auto sum(const std::vector<T>& vec) {
T result = T();
for (const auto& elem : vec) {
result += elem;
}
return result;
}
The greatest benefit is simplifying function definitions: when the return type of a function is complex or obvious, using return type deduction can make the code more concise.
We can be lazier, haha!