Hacker News new | ask | show | jobs
by jschwartzi 3583 days ago
The purpose of the type system in C++ is partly to encode semantics about the usage of a particular construct. For example, we might declare three or four types which all support the increment() function(or operator). The traditional way to do this is to create an interface and have the four concrete types inherit from the interface.

What auto says is "I don't care what type this value is. I just want it to support the semantics that I'm about to describe in this block." If you change the return type of the value in the auto expression, as long as the new return type supports the same semantics as the original return type, you don't need to touch that function after the refactor.

The compiler still complains when it can't find a way to make the return value support the semantics you're asking for. This is an improvement, but only in cases where you genuinely don't care what type it is, but only that it supports iteration. You still have to use auto with care, like every other keyword, but it does significantly improve maintainability in code bases where traditionally you would mechanically key in the same type information multiple times throughout the declaration of a class and its usage. Typedef and using statements solve similar problems, but they don't solve exactly the same problem.

For a good example of why this is a wonderful thing, try to determine what return type you should declare for an STL iterator, or try using Boost while avoiding the auto keyword.

1 comments

I'm currently working on a code base that's just upgrading to MSVC 10.0, and seeing std::vector::value_type(?)::const_iterator everywhere is killing me.