2010-09-14 38 views
1

我有一个ThingController的列表,我想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,是的,我知道它是旧的...

回答

4

您可以使用bind,它最初来自升压但包含在TR1和C + + 0X:

using std::tr1::placeholders::_1; 
std::for_each(things.begin(), things.end(), 
       std::tr1::bind(&Controller::notify, c, _1)); 
+0

感谢詹姆斯,这正是我一直在寻找。 – bstpierre 2010-09-14 00:26:00

3

关于去老派什么:

for(list<Thing>::iterator i = things.begin(); i != things.end(); i++) 
    c.notify(*i); 
+1

因为这太明显了? :)老实说,这是为了学习,我正在努力学习新派的做法。 – bstpierre 2010-09-14 00:20:44

相关问题