[英]boost::bind and class member function
Consider following example. 考虑以下示例。
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
void
func(int e, int x) {
std::cerr << "x is " << x << std::endl;
std::cerr << "e is " << e << std::endl;
}
struct foo {
std::vector<int> v;
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(func, _1, x));
}
void func2(int e, int x) {
std::cerr << "x is " << x << std::endl;
std::cerr << "e is " << e << std::endl;
}
};
int
main()
{
foo f;
f.v.push_back(1);
f.v.push_back(2);
f.v.push_back(3);
f.v.push_back(4);
f.calc(1);
return 0;
}
All works fine if I use func()
function. 如果我使用
func()
函数,一切正常。 But in real life application I have to use class member function, ie foo::func2()
in this example. 但在现实生活中,我必须使用类成员函数,即本例中的
foo::func2()
。 How can I do this with boost::bind ? 我怎么能用boost :: bind做到这一点?
You were really, really close: 你真的非常非常接近:
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(&foo::func2, this, _1, x));
}
EDIT: oops, so was I. heh. 编辑:哎呀,我也是。
Although, on reflection, there is nothing really wrong with your first working example. 虽然,经过反思,你的第一个工作实例并没有什么问题。 You should really favour free functions over member functions where possible - you can see the increased simplicity in your version.
在可能的情况下,您应该更喜欢免费功能而不是成员函数 - 您可以看到版本中增加的简单性。
While using boost::bind for binding class member functions, the second argument must supply the object context. 使用boost :: bind来绑定类成员函数时,第二个参数必须提供对象上下文。 So your code will work when the second argument is
this
因此,当第二个参数为
this
您的代码将起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.