Get attribute by name

后端 未结 5 2005
野的像风
野的像风 2020-11-30 13:15

I have a struct definition with about 25 elements

struct X { field 1; field 2; .. };    

and I\'m trying to fill it with some map values <

5条回答
  •  离开以前
    2020-11-30 13:43

    C++ lacks built-in reflection capabilities of more dynamic languages, so you cannot do what you would like using he out of the box capabilities of the language.

    However, if all members are of the same type, you can do it with a map of pointers to members and a little preparation:

     // typedef for the pointer-to-member
     typedef int X::*ptr_attr;
    
     // Declare the map of pointers to members
     map mattr;
     // Add pointers to individual members one by one:
     mattr["xx"] = &X::xx;
     mattr["yy"] = &X::yy;
    
    // Now that you have an instance of x...
     X x;
    // you can access its members by pointers using the syntax below:
     x.*mattr["xx"] = A["aa"];
    

提交回复
热议问题