How to use the result of __traits( allMembers , T ) with string mixins ?
ParticlePeter via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Apr 28 07:15:56 PDT 2014
On Monday, 28 April 2014 at 13:57:56 UTC, Andrej Mitrovic wrote:
> 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 ) );");
> }
> }
> -----
Thank you very much, it works. I never came so far to see those
mixin errors at all :-)
I found the code with parenthesis in the dlang __traits docs and
also Philippe Sigauds "D Templates", and I haven't seen any other
example which works without them. So, when to use which syntax (
for which purpose ) ? Is this clarified somewhere ?
Regards, ParticlePeter
More information about the Digitalmars-d-learn
mailing list