Return type deduction

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Sep 8 06:28:15 PDT 2016


On 9/7/16 3:19 AM, Andrea Fontana wrote:
> On Tuesday, 6 September 2016 at 14:21:26 UTC, Steven Schveighoffer wrote:
>> On 9/5/16 5:59 AM, Andrea Fontana wrote:
>>> I asked this some time (years?) ago. Time for a second try :)
>>>
>>> Consider this:
>>>
>>> ---
>>>
>>> T simple(T)() { return T.init; }
>>>
>>>
>>> void main()
>>> {
>>>     int test = simple!int(); // it compiles
>>>     int test2 = simple();    // it doesn't
>>
>>       auto test3 = simple!int();
>>
>> Granted, you are still typing "auto", but only specify the type once.
>>
>> -Steve
>
> Only for the simple case.
>
> It would interesting if it would work for:
>
> struct Blah
> {
>    string name;
> }
>
> Blah b;
> b.name = simple();
>
>
> or:
>
> void myFunc(string s) { ... }
> myFunc(simple());

Right, but there is a problem here. The connection of the simple return 
type to the simple template parameter is not necessarily guaranteed. 
That is, there is no guarantee simple!int is going to return int (for 
any template).

This means the compiler has to determine how to make simple return an 
int, and this isn't always obvious, or easy to determine.

You can, of course, rewrite simple to take advantage of IFTI:

void simple(T)(ref T setThis) { setThis = T.init; }

simple(b.name);

I'd call it initialize, and do it this way:

b.name.initialize();

-Steve


More information about the Digitalmars-d mailing list