How to get only the field name from an alias?

ryuukk_ ryuukk.dev at gmail.com
Tue Feb 21 03:13:38 UTC 2023


I'm not sure what the solution is for your specific question, but 
there is some alternative way you could do: (no longer need 
function on your struct)

I tried to comment the lines, even thought i'm not sure i 
remember everything correctly, but it compiles :p

More info: https://dlang.org/spec/traits.html

```D
import std.stdio;

class Serializer
{
     void process(string k, ref int v)
     {
         writeln("serializing int ", k, ": ", v);
     }

     void process(string k, ref long v)
     {
         writeln("serializing long ", k, ": ", v);
     }

     void process(U)(ref U v) if (is(U == struct))
     {
         // get all members from U
         static foreach (member; __traits(allMembers, U))
         {
             // get attributes from U.member
             static foreach (attr; __traits(getAttributes, 
__traits(getMember, U, member)))
             {
                 // is the attribute OldName
                 static if (is(typeof(attr) == OldName))
                 {
                     // the name you put in OldName attribute
                     string oldName = attr.name;
                     auto value = __traits(getMember, v, member);

                     writeln("field: ", member);
                     writeln("oldname: ", oldName);
                     writeln("value: ", value);
                 }
             }
         }
     }
}

struct OldName
{
     string name;
}

struct Serializable
{
     @OldName("ifield")
     int intField;
}

void main()
{
     import std.stdio;
     import std.traits;
     import core.internal.traits;

     Serializable v;
     auto sz = new Serializer();
     sz.process(v);
}
```


More information about the Digitalmars-d-learn mailing list