Seems like if you don't know whether you have an iterator for a map or a vector you wouldn't know whether to use first or second or just directly access properties of the object, no?

This reminds me of the C# debate on whether to use the keyword var. The impression I'm getting so far is that in the C++ world people are ready to adopt the auto keyword with less of a fight than var in the C# world. For me my first instinct is that I like to know the type of the variable so I can know what operations I can expect to perform on it.

Wait! There was a fight about whether to use var? I missed that.
–
pdrMay 12 '12 at 5:19

8

Even better, you can just use for (auto& it : x) (or without reference if you want copying)
–
Tamás SzeleiMay 12 '12 at 7:46

3

Seems to me if you're writing a loop to iterate over the contents of x and you don't even know what x is, you shouldn't write that loop in the first place ;-)
–
nikieMay 13 '12 at 9:10

@fish: range based for-loops rules, but I would have been pedantic and done: 'for (T& it : x)' instead when using range based for-loops, as I feel using auto there is less informative. Kind of a misuse of auto in my mind.
–
martiertJan 3 '13 at 13:41

The motivations in C++ are more extreme, as types can become vastly more convoluted and complex than C# types due to metaprogramming and other things. auto is faster to write and read and more flexible/maintainable than an explicit type. I mean, do you want to start typing

And in all cases, the answer is the same: Context matters. You can’t meaningfully talk about a piece of code in isolation. Even if you hadn’t used templates but some concrete type, this would only have moved the problem somewhere else, since the reader of your code would have to know about the declaration of said type.

If use of auto in those situations render your code unreadable you should treat this as a warning sign that there’s something wrong with your code design. Of course, there are cases where low-level details matter (such as when dealing with bit operations or legacy API) in which cases an explicit type might aid readability. But in general – no.

Regarding var (since you explicitly mentioned it), there’s also a vast consensus in the C# community for using var. Arguments against its use are generally built on fallacies.

YES, you should! auto does not erase the type; even if you "don't know" what x.begin() is, the compiler knows and will report an error if you try to use the type wrongly. Also, it is not unusual to emulate map with a vector<pair<Key,Value>>, so the code using auto will work for both dictionary representations.