auto: useful, annoying or bad practice?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed May 9 15:06:55 UTC 2018


On Wednesday, May 09, 2018 14:31:00 Jesse Phillips via Digitalmars-d wrote:
> On Wednesday, 9 May 2018 at 13:22:56 UTC, bauss wrote:
> > Using "auto" you can also have multiple return types.
> >
> > auto foo(T)(T value)
> > {
> >
> >     static if (is(T == int)) return "int: " ~ to!string(value);
> >     else return value;
> >
> > }
> >
> > You cannot give that function a specific return type as it's
> > either T or it's string. It's not a single type.
>
> Its funny, because you example makes this look like a very bad
> feature. But there are legitimate cases which doesn't actually
> chance the api of the returned type.

Basically, it falls into the same situation as ranges and Voldemort types.
If you have a situation where it doesn't make sense to restrict the return
type to a specific type, where the return type depends on the template
arguments, or where the return type should be hidden, then auto is great.
But in all of those situations, the API has to be well-known, or the caller
can't do anything useful. Worst case, you end up with a base API that's
common to all of the return types (e.g. forward range) but where you have to
test whether a particular set of template arguments results in a return type
which supports more (e.g. a random-access range).

Ultimately, the key is that the user of the function needs to be able to
know how to use the return type. In some cases, that means returning a
specific type, whereas in others, it means using auto and being clear in the
documentation about what kind of API the return type has. As long as the API
is clear, then auto can be fantastic, but if the documentation is poorly
written (or non-existant), then it can be a serious problem.

- Jonathan M Davis



More information about the Digitalmars-d mailing list