1

我有一个清单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,是的,我知道它很旧......

4

2 回答 2

4

您可以使用 来完成此操作bind,它最初来自 Boost,但包含在 TR1 和 C++0x 中:

using std::tr1::placeholders::_1;
std::for_each(things.begin(), things.end(),
              std::tr1::bind(&Controller::notify, c, _1));
于 2010-09-14T00:15:35.557 回答
3

去老学校怎么样:

for(list<Thing>::iterator i = things.begin(); i != things.end(); i++)
  c.notify(*i);
于 2010-09-14T00:18:30.313 回答