2010-09-14 86 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

相關問題