Get attribute by name

混江龙づ霸主 提交于 2019-11-27 05:20:40

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"];

Short answer: no. This is C++, a statically compiled language, where the structure member names are converted by the compiler into memory offsets. It is not dynamic like PHP or Python where the runtime is involved with all variable references.

No. C++ doesn't have reflection. Java does though. Unsurprisingly, SOA related stuff is more probably encountered with languages like Java than it is with languages like C.

It's not really possible to do that; the information you need is no longer present at runtime. You might be able to do something with a map and some pointers, but to be honest you would probably be better off just wrapping it up in a function that takes a map and puts the values into the appropriate fields.

You could create a wrapper objet for your struct with set/get accessors that will let you iterate over string values for filling/reading the underlying struct that is static.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!