C ++:迭代所有的对象的成员? [英] C++: Iterating through all of an object's members?

查看:225
本文介绍了C ++:迭代所有的对象的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个拥有许多成员的对象:

Suppose I have an object with many members:

class Example {
    AnotherClass member1;
    AnotherClass member2;
    YetAnotherClass member3;
    ...
};

是否有简短的方法来做:

Is there a short/concise way to do something like:

foreach(member m: myExample)
    m.sharedMethod();

而不是逐一存取每个?

我想我可以把它们放在一个向量,并使用 shared_ptr 为同样的效果,我只是想知道如果说,Boost或一些其他流行的图书馆没有东西自动执行此操作。

I think I could put them in a vector and use a shared_ptr for the same effect, I was just wondering if say, Boost or some other popular library doesn't have something to do this automatically.

推荐答案

C ++不支持类自省,因此不能遍历类中的所有成员

C++ does not support class introspection, so you cannot iterate over all of the members in a class like that - not without having a (manually written) function that iterates over all members for you anyway.

原则上,您可以添加一个模板成员,如下所示:

You could, in principle, add a template member like so:

template<typename Functor>
void doAllMembers(Functor &f) {
  f(member1);
  f(member2);
  f(member3);
}

也就是说,我认为这是一个破碎的设计;你已经公开了你的所有内部成员。如果以后添加,会发生什么?或者改变一个的语义?将一个缓存的值设置为有时已过期?

That said, I would regard this as a broken design; you've gone and exposed all of your internal members publicly. What happens if you add one later? Or change the semantics of one? Make one a cached value that's sometimes out of date? etc. Moreover, what happens if you have members which don't all inherit from the same types?

退回并重新考虑您的设计。

Step back and reconsider your design.

这篇关于C ++:迭代所有的对象的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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