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

Dicebot via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 28 11:20:39 PDT 2014


On Monday, 28 April 2014 at 17:40:54 UTC, Philippe Sigaud via 
Digitalmars-d-learn wrote:
> On Mon, Apr 28, 2014 at 5:45 PM, Andrej Mitrovic via
> Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
>
>> If you need to store the tuple as an array to some variable, 
>> then you
>> would use that syntax. It all depends on what you're trying to 
>> do from
>> the call site. Ultimately it won't matter much once we finally 
>> get a
>> proper 'static foreach' feature in D.
>
> I guess a common use case is to create an array  with 
> [__traits(...)],
> and use it inside a function, iterating on it and creating a 
> string
> with the elements. The string is then mixed in with a CTFE call.
>
> string makeCode(...) {
>     enum members = [ __traits(allMembers, MyStruct) ];
>
>     string result;
>     foreach (m; members)
>     {
>         result ~= "writeln( `" ~ m ~ "` , \" : \" , ( 
> MyStruct." ~ m ~
> ".offsetof ) );");
>     }
>     return result;
> }
>
> mixin(makeCode());
>
> I don't know what I used it for in the tutorial, though :-)

You can do the same iterating directly over allMembers list, why 
would you prefer array here?


More information about the Digitalmars-d-learn mailing list