Using std traits

Ali Çehreli acehreli at yahoo.com
Thu Jan 25 19:57:20 UTC 2018


On 01/25/2018 11:49 AM, JN wrote:

>          foreach (i, member; FieldNameTuple!T)
>          {
>              if (!hasUDA!(member, "noserialize"))
>              {
>                  writeln(member);
>              }

'member' is a string local variable, which does not have that UDA. You 
need to get the symbol of the struct:

             if (!hasUDA!(__traits(getMember, T, member), "noserialize"))
             {
                 writeln(member);
             }

However, note that you're using a compile-time foreach, which expands 
its body for each iteration. Since you used a regular if, you have three 
checks at runtime.

What you really want is use a 'static if':

             static if (!hasUDA!(__traits(getMember, T, member), 
"noserialize"))
             {
                 writeln(member);
             }

Aaah... Much lighter... :)

Even further, you may want to consider using a 'static foreach':

         static foreach (i, member; FieldNameTuple!T)
         {
             // ...
         }

That is more powerful because it can iterate over more ranges. However 
there are some differences from the regular foreach: For example, 
'static foreach' does not introduce a scope per iteration.

Ali


More information about the Digitalmars-d-learn mailing list