C ++ Structs:按名称获取属性 [英] C++ Structs: get attribute by name

查看:167
本文介绍了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"];

这篇关于C ++ Structs:按名称获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆