【发布时间】:2010-09-14 00:09:50
【问题描述】:
我有一个Thing 和一个Controller 的列表,我想用notify() 来处理每一件事。下面的代码有效:
#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,是的,我知道它很旧...
【问题讨论】: