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

Bastiaan Veelo Bastiaan at Veelo.net
Wed Sep 8 21:25:23 UTC 2021


On Tuesday, 7 September 2021 at 17:24:34 UTC, james.p.leblanc 
wrote:
>
> ```d
> /*…*/
>
>    // 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);
>    // }
> }
>
> ```

As Adam mentioned `tupleof` only exists at compile time, and a 
`foreach` over a `tupleof` gets unrolled at compile time, akin to 
a `static foreach`. Consequently you can make your snippet work 
by prepending `static` (and fixing the range):

```d
static foreach (i; 0 .. u.tupleof.length) {
        ptr = u.tupleof[i].x.ptr;
        writeln("ptr: ", ptr);
}
```
https://run.dlang.io/is/T6jrjf

Not sure if that helps in what you’re trying to achieve though, 
as that isn’t clear to me.

—Bastiaan.



More information about the Digitalmars-d-learn mailing list