Referencing structs in a foreach

Alf via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 23 10:23:12 PDT 2014


Thanks for your reply.
I figured an easier way would be to simply build an array of 
references:

   foreach (ref f; [&bar.f1, &bar.f2])
   {
     f.a++;
     f.b++;
   }

It seems to work just fine.

Alf

On Wednesday, 23 July 2014 at 01:41:33 UTC, Dicebot wrote:
> On Wednesday, 23 July 2014 at 01:31:48 UTC, Alf wrote:
>>  foreach (ref f; [bar.f1, bar.f2])
>
> This allocates new array and copies struct values to it (as D 
> structs are value types). I think this should have been a 
> compile-time error btw, it never makes sense to do ref 
> iteration over an array literal for this very reason.
>
> Most likely you want to forced loop unrolling here and thus 
> something like this:
>
>>  import std.typetuple;
>>  foreach (ref f; TypeTuple!(bar.f1, bar.f2))
>
> (don't pay attention to the weird "TypeTyple" name, it lies)



More information about the Digitalmars-d mailing list