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

查看:133
本文介绍了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();

而不是单独访问每个人的?

Instead of accessing each one individually?

我想我可以把它们放在一个载体,并使用的shared_ptr 对于同样的效果,我只是说,如果想知道,升压或其他一些流行的库不有事要自动执行此操作。

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天全站免登陆