Yet another MRV proposal!

downs default_357-line at yahoo.de
Mon Apr 14 03:23:31 PDT 2008


Simen Kjaeraas wrote:
> On Mon, 14 Apr 2008 11:23:50 +0200, downs <default_357-line at yahoo.de>
> wrote:
> 
>> Let's give this another try.
>> The following proposal has the advantage that it's funded mostly on
>> existing syntax.
>>
>> An anonymous struct, in the position where you'd normally expect a
>> function/method return type, is usable as the return type instead.
>>
>> Example:
>>
>> struct { int a; float b; } test() { return(1, 2f); }
>>
>> writefln(test().a, test().b);
>>
>> The compiler would translate this into "current D" as follows:
>>
>> struct _D_anonymous_struct_1 { int a; float b; }
>> _D_anonymous_struct_1 test() { return _D_anonymous_struct_1(1, 2f); }
>>
>> Because of the not-exactly-clear type name, it is necessary to store
>> the returned value in an auto/const/static variable.
>>
>> This looks like it could be ambiguous, but it really isn't - the two
>> conditions required here - an unnamed struct in the position where a
>> return type would be expected - are quite unambiguous :)
>>
>> Whaddya think?
>>
>>  --downs
> 
> 
> Looks pretty good - there are reasons to allow returning anonymous
> structs, and I'm sure they could find uses in other places as well.
> 
> One problem I see is that, compared to 'true' MRV, it requires extra
> assignments if you want the values outside the struct.
> 
>   int a;
>   float b;
> 
>   struct { int a; float b; } test() { return(1, 2f); }
> 
>   auto result = test();
> 
>   a = result.a; // These should
>   b = result.b; // be redundant
> 
> compared to:
> 
>   int a;
>   float b;
> 
>   // some weird syntax for MRVs
>   [int, float] test() { return (1, 2f); }
> 
>   a, b = test(); // More prettiful
> 

Well, I see two ways around that ..

the first is "with (test()) { use a and b here; }"

the second is to allow mixins to work on non-templates, so you could mixin test() to get a and b in the current scope.

the third is to use some type of struct variable holder using pointers, that allows assignment from same-layout other-type structs
so, int a; float b; ptuple(a, b) = test(); // this could work in current D

> Now, if struct could have reference members...
> 
>   int a;
>   float b;
> 
>   struct { int a, float b} test() { return(1, 2f); }
> 
>   struct { ref a; ref b; } = test();
> 
> or:
> 
>   int a;
>   float b;
> 
>   [int, float] test() { return(1, 2f); }
> 
>   [ref a, ref b] = test();
> 
> 
> With all that said, I really like your proposal, and I hope it gets
> implemented.
> 
> -- Simen

Yay, thanks! :D

 --downs



More information about the Digitalmars-d mailing list