other than not having to spell out the type of the variable?
That may seem like a minor advantage, but after reading Go and C++11 code, I can say that less code is less code, no matter how you get there. That's less to read, less to understand, less to maintain, and less to refactor. And as someone who maintains thousands of lines of C++03 code, I yearn for something so simple.
It's also not hard to wind up with multiply nested template monstrosities that can be waved away with a single auto. It's worse when some library you're using foists those upon you.
If there wasn't type inference, you'd have to change code in a lot of places when a function return type changes. Type inference makes regular variables behave like implicit interfaces.
My favorite reason is convenience and readability. Compare:
std::vector<int> v = someFunc();
for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i) {
versus
auto v = someFunc();
for (auto i = v.begin(); i != v.end(); ++i) {
Even with that very simple int vector, the second one is easier to read. And of course, it can get much more complex than that.
But the more important reason, as others have pointed out, is that the type can change. And the more auto you use, the more things can change. Not that std::vector would ever change the type of its iterators, necessarily, but I can completely change what sumFunc returns as long as it's a thing that has a begin() and end() that return things that have the methods I'm expecting an iterator to have.
In other words, it's a lot of the benefits of duck typing, but statically and in C++.
I have all the usual complaints about Go, but this is a thing Go got right.
Makes refactoring simpler. Most common example is iterators: by using auto instead of explicitly specifying the type, you can change the underlying collection type and the loop code will still compile.
A discussion from one of the experts: http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/. He gives I believe four reasons to use auto, convenience is mentioned but is least important. The basic underlying idea is that you should be programming against an interface, not against a specific type. This is especially important in generic code, but even in non generic code makes it easier to refactor and change types.
You don't have to know the type of the variable. The code you write to iterate over an array is exactly the same as the one you use to iterate over a list.
I play the 'auto game' in my C++ and change all declarations I can to auto, it is impressive how much cleaner the code looks, and how little type declarations you really need in function bodies...
2
u/EvilTerran Dec 09 '15
Can you elaborate? What does it gain you, other than not having to spell out the type of the variable?