我有一个Thing
和Controller
的列表,我想notify()
与每件事情。下面的代码工作:用列表中的每个元素调用C++成员函数?
#include <algorithm>
#include <iostream>
#include <tr1/functional>
#include <list>
using namespace std;
class Thing { public: int x; };
class Controller
{
public:
void notify(Thing& t) { cerr << t.x << endl; }
};
class Notifier
{
public:
Notifier(Controller* c) { _c = c; }
void operator()(Thing& t) { _c->notify(t); }
private:
Controller* _c;
};
int main()
{
list<Thing> things;
Controller c;
// ... add some things ...
Thing t;
t.x = 1; things.push_back(t);
t.x = 2; things.push_back(t);
t.x = 3; things.push_back(t);
// This doesn't work:
//for_each(things.begin(), things.end(),
// tr1::mem_fn(&Controller::notify));
for_each(things.begin(), things.end(), Notifier(&c));
return 0;
}
我的问题是:我可以得到使用“这行不通”行的某些版本摆脱Notifier
类的?似乎我应该能够做出一些工作,但不能完全正确地组合。 (我已经摸索了一些不同的组合。)
没有使用提升? (我会如果我能。)我使用g ++ 4.1.2,是的,我知道它是旧的...
感谢詹姆斯,这正是我一直在寻找。 – bstpierre 2010-09-14 00:26:00