How get struct value by member name string ?

John Xu 728308756 at qq.com
Wed May 31 04:08:18 UTC 2023


On Tuesday, 30 May 2023 at 15:43:12 UTC, Steven Schveighoffer 
wrote:
> On 5/30/23 4:46 AM, John Xu wrote:
>> How to put above enum as a function parameter? Following code 
>> wouldn't work:
>> 
>>      string getTMember(T t, enum string memberName) {
>>          return __traits(getMember, t, memberName);
>>      }
>
> compile time parameters come before runtime parameters:
>
> ```d
> string getTMember(string memberName)(T t) {
>    return __traits(getMember, t, memberName);
> }
>
> // used like
> auto v = getTMember!"name"(t);
> ```
>
> -Steve

When render vibe.d diet template,

     string[] 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.


More information about the Digitalmars-d-learn mailing list