使用 for_each 调用带有成员数据的成员函数
亲爱的大家,我想为(比方说)属于同一类的成员的向量的每个对象调用一个成员函数(需要引用),如以下代码所示:
#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
struct Stuff {
double x;
};
class Test {
public:
void f1(Stuff & thing);
void f2(void);
vector<Stuff> things;
};
void Test::f1(Stuff & thing) {
; // do nothing
}
void Test::f2(void) {
for_each(things.begin(), things.end(), f1);
}
int main(void)
{
return 0;
}
此代码给了我一个相关的编译器错误到未解析的重载函数类型。我也尝试过使用绑定,但似乎 f1 中所需的引用是一个问题。我知道我在这里错过了一些重要的东西,所以我借此机会解决我的问题并学习。目前,我无法安装boost,但我也想知道boost是否有助于解决这个问题。提前致谢。
Dear all, I would like to call a member function (that expects a reference) for each object of (let's say) a vector that is a member of the same class, as the following code shows:
#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
struct Stuff {
double x;
};
class Test {
public:
void f1(Stuff & thing);
void f2(void);
vector<Stuff> things;
};
void Test::f1(Stuff & thing) {
; // do nothing
}
void Test::f2(void) {
for_each(things.begin(), things.end(), f1);
}
int main(void)
{
return 0;
}
This codes gives me a compiler error related to unresolved overloaded function type . I have tried also with bind, but it seems that the references requisite in f1 is one problem. I know I am missing something important here, so I take this opportunity to solve my problem and to learn. At the moment, I can't install boost, but I would like to know also if boost is useful to solve this problem. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
f1
标识,而应称为&Test::f1
(如:成员函数f1Test
的 code>)f1
不接受单个参数:与任何非静态成员函数一样,它有一个隐式this
参数typeTest * const
Boost.Bind 确实是一个不错的选择:
f1
but should be referred to as&Test::f1
(as in : member functionf1
of classTest
)f1
does not take a single argument : as any non-static member function it has an implicitthis
parameter of typeTest * const
Boost.Bind would indeed be a great option :