按名称获取属性 [英] Get attribute by name

查看:84
本文介绍了按名称获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个约有25个元素的结构定义

  struct X {字段1;领域2; ..}; 

我正在尝试用一些地图值填充

  Map< String,String> 

似乎很讨厌n次这样做

  X-> xx = A [ aaa] 

每一次我想填充消息结构。



是否可以通过名称访问成员,例如

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

并使其循环?

解决方案

C ++缺少更多动态语言的内置 reflection 功能,因此您无法使用该语言的即用型功能来完成您想做的事情。 / p>

但是,如果所有成员都属于同一类型,则可以通过指向成员的指针映射和一些准备工作来实现:

  //指向成员的指针
的typedef int X :: * ptr_attr;

//声明指向成员的指针的地图
map< string,ptr_attr> mattr;
//一对一地添加指向单个成员的指针:
mattr [ xx] =& X :: xx;
mattr [ yy] =& X :: yy;

//现在您有了x ...的实例
X x;
//您可以使用以下语法通过指针访问其成员:
x。* mattr [ xx] = A [ aa];


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?

解决方案

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

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

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