How get struct value by member name string ?

John Xu 728308756 at qq.com
Fri Jun 2 02:58:52 UTC 2023


On Thursday, 1 June 2023 at 15:38:08 UTC, Steven Schveighoffer 
wrote:
> On 5/31/23 12:08 AM, John Xu wrote:
>
>> 
>> When render vibe.d diet template,
>> 
>>      string[] allMembers = __traits(allMembers, t);
>
> enum allMembers = __traits(allMembers, t);
>
>>      res.render!("index.dt", t, allMembers)
>> 
>> if I don't want write memberName one by one in diet template:
>> 
>>      table
>>          - foreach(memberName; allMembers)
>>              tr
>>                  td #{memberName}
>>                  td #{getTMember!memberName(t)}
>> 
>> Problem: memberName is not known at compile time.
>
> The problem is that you stored the member name list as a 
> runtime variable, and that is not known at compile time. Try 
> the enum.
>
> Or really, just `foreach(memberName; __traits(allMembers, t))` 
> right in the diet template.
>
> -Steve

Ok, thanks for all you gentlemen's help. I tried following 
function,
now it works like C/C++/Python way:

     string getTMember(T t, string columnName) {
         foreach(member; __traits(allMembers, T)){
             if (member == columnName) {
                 return __traits(getMember, mcu, member).to!string;
             }
         }
         return "";
     }



More information about the Digitalmars-d-learn mailing list