Phobos examples and auto

Jonathan M Davis jmdavisProg at
Sun Nov 6 01:20:46 PDT 2011

On Sunday, November 06, 2011 00:37:50 Andrei Alexandrescu wrote:
> On 11/5/11 11:29 PM, Steve Teale wrote:
> > Can you write us a brief article that will convince me of its benefits,
> > and the error of my ways please. There's no Borders where I live, and
> > Amazon does not deliver to Africa, so I don't have the benefit of your
> > book.
> Unfortunately my schedule doesn't allow it, but sounds like a good
> article idea.

A few of the reasons are

1. Some functions (especially those in std.algorithm) return templated types 
which you _don't_ want to have to type yourself or even worry about or care 
what they are beyond the fact that they're a range. auto makes such functions 
quite usable and useful whereas as they would be completely unreasonable 
otherwise. So, ranges in general definitely are used with auto.

2. With auto, if you change the type, you often don't have to change the code. 
For instance, if you have a function which returns a particular type, and you 
use auto, then if you change the type that it returns later and the new type 
has same API (or close enough that it doesn't matter for your code), then you 
don't have to change any of your code, whereas if you didn't use auto, you 
would. So, auto tends to make refactoring much easier.

3. Code tends to be more concise with auto. You avoid having to repeat the 
type name on both sides of the assignment operator.

I'm sure that there are more good reasons to use auto, but those are just a 
few of them that come immediately to mind. Honestly, when I first ran into 
auto, I didn't think that it was a big deal or that it was even necessarily a 
good idea, but after having used in code, I've found it to be _very_ useful. 
In fact, it drives me nuts when I can't use it in C++ - especially when you 
have to declare variables with types like vector<int>::iterator. I'll be 
_very_ glad when I get to use C++11 instead of C++98/03, since it adds auto. 
And actually, since it adds auto, you can probably find some good reasons for 
using it explained for C++11 if you go searching for them.

Overall, I just find that auto makes code cleaner, more legible, and easier to 
maintain. So, I pretty much always use it unless I can't (e.g. when a variable 
is default-initialized or when a variable's initializers defaults to the wrong 
type - which tends to happen with size_t). Perhaps, some examples should use 
it less in order to provide more clarity, but in general, I don't think that 
it's a big deal, because you can just look at the function's return type, 
which in most cases is right after the example that you're looking at, because 
the example is for the function in question.

- Jonathan M Davis

More information about the Digitalmars-d mailing list