C ++ Structs:按名称获取属性

问题描述:

我想要一个更专业的解决方案的问题。
我正在使用C ++ SOAP2解决方案。我有一个大约25个元素的Strcut定义

I'm wondring for a more professional solution for a problem. I'm working on C ++ SOAP2 solution.I have a Strcut defintion of about 25 elements

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

我正在填充一些地图值

Map<String,String> A    

并且看起来很讨厌做这样的事n次

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

X->xx = A["aaa"]    

$ b $

问题:是否可以通过名称调用struct element?
* example:to be abe to process like this:

Question : Is it possible to call struct element by name? *example: to be abe to process like this :

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

并将其放入循环中。
*

and put it into a loop .. *

感谢,

C ++缺少内置的反射动态语言,所以你不能做你想要的使用他的框的能力的语言。

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