How to use the result of __traits( allMembers , T ) with string mixins ?

Andrej Mitrovic via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 28 06:57:55 PDT 2014


On Monday, 28 April 2014 at 13:52:52 UTC, ParticlePeter wrote:
> DMD tells me "Error: variable m cannot be read at compile 
> time", but why ?

Because 'static foreach' is not an explicit feature yet, so it 
depends on the context. When you wrap the trait via:

[__traits(allMembers, MyStruct)]

You're creating an array, and foreach will *not* by default 
attempt to become a static foreach, even if the array is known at 
compile-time. If you remove the parentheses it will work. You've 
had a few bugs in the mixin code though, anyway here's the 
working sample:

-----
import std.stdio;

struct MyStruct
{
     float float_value = 0.0f;
     ubyte ubyte_value = 2;
}

enum members = __traits(allMembers, MyStruct);

void main()
{
     foreach (m; members)
     {
         mixin("writeln( `" ~ m ~ "` , \" : \" , ( MyStruct." ~ m 
~ ".offsetof ) );");
     }
}
-----


More information about the Digitalmars-d-learn mailing list