boost :: bind和类成员函数 [英] boost::bind and class member function
本文介绍了boost :: bind和类成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下示例。
#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;
}
如果我使用 / code>函数。但在现实生活中,我必须使用类成员函数,即
foo :: func2()
。我如何做到这一点与boost :: bind?
All works fine if I use func()
function. But in real life application I have to use class member function, i.e. foo::func2()
in this example. How can I do this with boost::bind ?
推荐答案
你真的,真的很近:
void calc(int x) {
std::for_each(v.begin(), v.end(),
boost::bind(&foo::func2, this, _1, x));
}
编辑:oops,所以是I. heh。
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.
这篇关于boost :: bind和类成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文