Using consistently auto as function return type

Timon Gehr timon.gehr at gmx.ch
Sat Jun 16 04:18:29 PDT 2012


On 06/16/2012 11:31 AM, Tommi wrote:
> Do you consider it to be good or bad style of programming to use
> consistently auto as function return type?
>
> One of the pros is that it saves some redundant typing when the function
> returns some complex templated type:
>
> auto getValue()
> {
>      return MyType!(int, "asdf", 64).init;
> }
>
> But one of the cons is that you don't see what the function returns just
> by looking at the signature.
>
> Are there some more severe issues that I'm missing?

auto return types make functions semantically dependent on each other,
eg. the following is illegal code:

auto foo(){bar(); return 0; }
auto bar(){foo(); return 1; }

In order to resolve the return type of foo, the body of foo needs to be
analyzed, which involves resolving the return type of bar, therefore
the body of bar needs to be analyzed, which involves resolving the
return type of foo, therefore the body of foo needs to be analyzed, ...


The current implementation is very conservative, and rejects every
dependency cycle of auto return functions, even if the return types
could be resolved in theory.


Other than that, there are no more severe issues, I see these major
applications for auto return types:

- The body is very short and spells out the type explicitly, auto saves 
redundancy.

- The implementer does not know the exact return type himself, because
   it depends on template arguments.

- The user of the function does not need to know the return type. eg if
   it is a type local to the function.


More information about the Digitalmars-d-learn mailing list