Curious effect with traits, meta, and a foreach loop ... mystifies me.

james.p.leblanc james.p.leblanc at gmail.com
Tue Sep 7 17:24:34 UTC 2021


Dear All,

In playing with some reflection and meta programming, this 
curiosity
appeared.

Does someone understand what is happening?  I would appreciate 
learning
about it if possible.  Enclosed code snippet tells the story:

```d
import std.stdio;
import std.traits;
import std.meta;

struct  S0{ double[3] x; };
struct  S1{ double junk0 ; double[3] x; };

union U { S0 s0;  S1 s1; }

void main(){

    U u;

    double* ptr;

    u.s0.x = [ 0.0, 0.1, 0.3 ];
    u.s1.x = [ 1.0, 1.1, 1.3 ];

    writeln("typeid( u.tupleof): ",    typeid( u.tupleof ) );
    writeln("typeid( u.tupleof[0]): ", typeid( u.tupleof[0] ) );
    writeln("typeid( u.tupleof[0].x): ", typeid( u.tupleof[0].x ) 
);

    writeln();

    // indeed both tuples exist
    writeln("u.tupleof[0].x.ptr: ", u.tupleof[0].x.ptr  );
    writeln("u.tupleof[1].x.ptr: ", u.tupleof[1].x.ptr  );

    // this is fine (notice that 'val' is never used
    foreach( i, val ; u.tupleof ){
       ptr = u.tupleof[i].x.ptr;
       writeln("ptr: ", ptr);
    }

    // this fails with: "Error: variable 'i' cannot be read at 
compile time
    //
    // foreach( i ; 0 .. 3 ){
    //    ptr = u.tupleof[i].x.ptr;
    //    writeln("ptr: ", ptr);
    // }
}

```

Best Regards,
James



More information about the Digitalmars-d-learn mailing list