考虑以下示例。
#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;
}
如果我使用一切正常func()
功能。但在现实生活中的应用程序中我必须使用类成员函数,即foo::func2()
在这个例子中。我怎样才能用 boost::bind 做到这一点?
你们真的非常非常接近:
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(&foo::func2, this, _1, x));
}
编辑:哎呀,我也是。呵呵。
不过,经过反思,您的第一个工作示例并没有什么真正的问题。在可能的情况下,您确实应该更喜欢自由函数而不是成员函数 - 您可以看到您的版本更加简单。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)