访问 C++ 中的成员动态和静态结构
我想在 C++ 中有一个结构(或类似的东西),它允许动态访问其成员。它应该有一个通用的 getter 和 setter,以字符串形式接收成员名称,并返回某种变体类型(例如 boost::variant
)。
我认为它可以使用 boost::fusion::map 来实现,通过添加一个表示每个成员名称的字符串,并在字符串和 getter 或 setter 函数之间构建 STL 映射。我不想重新发明轮子,所以我希望类似的东西已经存在。
你怎么认为?我的想法可行吗?您知道实现我的目标的其他方法吗?
I would like to have a struct (or something similar) in C++, that will allow access to its members dynamically. It should have a generic getter and setters that receive the member name as a string, and return some sort of variant type (e.g. boost::variant
).
I was thinking it could be implemented using boost::fusion::map
, by adding a string representing the name of each member, and building an STL map between strings and getter or setter functions. I don't want to reinvent the wheel, so I was hoping something similar already existed.
What do you think? Would my idea work? Do you know other ways to accomplish my goal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fusion 是一种方法,但为什么不将您的“字段”存储在由
std::string
键控的std::map
中,其中有效负载是boost ::variant
...即
然后你可以在 getter/setter 中查找键...
哎呀,将
variant
包装在可选
中,然后你可以有可选字段!一个更复杂的例子:
fusion is an approach, but why not store your "fields" in a
std::map
keyed by astd::string
, where the payload is theboost::variant
...i.e.
and then you can just lookup the key in your getter/setter...
heck, wrap the
variant
in anoptional
and you could have optional fields!a more complex example:
您正在要求 C++ 中的Reflection,我认为这是不可用的。你必须想出一些你自己的东西。
You are asking for Reflection in C++ which I think is not available. You will have to come up with something of your own.
我为此所做的是一个类似于 boost::cons 的类型列表,其中包含我的成员和某种描述。然后,我通过“链接”函数调用将我的成员连续添加到“元信息”数据结构中来构建此映射。整个事情看起来与在 boost.python 中定义一个类非常相似。如果您实际使用 boost::cons,它也应该作为 boost.fusion 中的序列工作,这样您就可以很好地迭代数据。也许您可以使用 boost.fusion 映射来在运行时获取 log(n) 访问时间,但在可变参数模板可用之前,它们的大小似乎受到限制。
What I did for this was a boost::cons-like type-list that contains my members and some kind of description. I then build this mapping by successively adding my members to a "meta-info" data structure by "chained" function calls. The whole thing looks very similar to defining a class in boost.python. If you actually use boost::cons, it should also work as a sequence in boost.fusion, so you can iterate nicely over your data. Maybe you can use a boost.fusion map instead to get log(n) access times at run-time, but it seems their size is limited until variadic templates are available.