Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Map<String,String> A    

and it appears to be very annoying to do such thing n times

X->xx = A["aaa"]    

every time that I want to fill my message struct.

Is it possible to access the members by name, e.g.

X->get_instance_of("xx").set(A["aaa"]);    

and put it into a loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

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<string,ptr_attr> 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"];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...