With GCC 4.8.0 released, we have a compiler that supports automatic return type deduction, part of C++14. With -std=c++1y
, I can do this:
auto foo() { //deduced to be int
return 5;
}
My question is: When should I use this feature? When is it necessary and when does it make code cleaner?
Scenario 1
The first scenario I can think of is whenever possible. Every function that can be written this way should be. The problem with this is that it might not always make the code more readable.
Scenario 2
The next scenario is to avoid more complex return types. As a very light example:
template<typename T, typename U>
auto add(T t, U u) { //almost deduced as decltype(t + u): decltype(auto) would
return t + u;
}
I don't believe that would ever really be a problem, though I guess having the return type explicitly depend on the parameters could be clearer in some cases.
Scenario 3
Next, to prevent redundancy:
auto foo() {
std::vector<std::map<std::pair<int, double>, int>> ret;
//fill ret in with stuff
return ret;
}
In C++11, we can sometimes just return {5, 6, 7};
in place of a vector, but that doesn't always work out and we need to specify the type in both the function header and the function body. This is purely redundant, and automatic return type deduction saves us from that redundancy.
Scenario 4
Finally, it can be used in place of very simple functions:
auto position() {
return pos_;
}
auto area() {
return length_ * width_;
}
Sometimes, though, we might look at the function, wanting to know the exact type, and if it isn't provided there, we have to go to another point in the code, like where pos_
is declared.
Conclusion
With those scenarios laid out, which of them actually prove to be a situation where this feature is useful in making the code cleaner? What about scenarios I have neglected to mention here? What precautions should I take before using this feature so that it doesn't bite me later? Is there anything new this feature brings to the table that isn't possible without it?
Note that the multiple questions are meant to be an aid in finding perspectives from which to answer this.
See Question&Answers more detail:
os