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 に答える