我有一個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