gpt4 book ai didi

c++ - 用列表中的每个元素调用 C++ 成员函数?

转载 作者:行者123 更新时间:2023-11-30 00:41:25 24 4
gpt4 key购买 nike

我有一个 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 类吗?好像我应该能够做一些工作,但不能完全得到正确的组合。 (我摸索过许多不同的组合。)

不使用 boost? (如果可以的话,我会的。)我正在使用 g++ 4.1.2,是的,我知道它很旧...

最佳答案

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

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

关于c++ - 用列表中的每个元素调用 C++ 成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com