Deducing a template retrun parameter type based on an assignment?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 30 06:31:33 PST 2015


On 1/30/15 5:06 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm at gmx.net>" 
wrote:
> On Friday, 30 January 2015 at 08:52:41 UTC, bearophile wrote:
>> Jeremy DeHaan:
>>
>>> I figured that it would be smart enough to
>>> deduce the parameter type based on the type that it was trying to be
>>> assigned to.
>>
>> For that you need languages like Haskell/Rust. D type inference
>> doesn't work from the type something is assigned to.
>
> But it could, right (for arguments and return expressions, too)? At
> least I don't see any real obstacles. Just file an enhancement request
> if you think it's worthwhile, or start a discussion on digitalmars.D.
>
> Of course, it cannot work for `auto x = getString();` or
> `foo(getString())` where there are several overloads of `foo()`. The
> next step would then be overloading on the return type, which is related.

Walter made a conscious decision not to depend on return types for 
overloads or any other deduction. It makes implementation of the 
language simpler. C++ has tremendously complex rules for overloading 
because of this.

Note, you can easily change this:

string x = getString();

to this:

auto x = getString!(char)();

which is still DRY.

One possible mechanism for working around this for when you already have 
a variable is to change the return value into a parameter

void getStringParam(T)(ref T[] x) if ... { x = getString!(T)(); }

-Steve


More information about the Digitalmars-d-learn mailing list