[英]boost::bind and class member function
考慮以下示例。
#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));
}
編輯:哎呀,我也是。
雖然,經過反思,你的第一個工作實例並沒有什么問題。 在可能的情況下,您應該更喜歡免費功能而不是成員函數 - 您可以看到版本中增加的簡單性。
使用boost :: bind來綁定類成員函數時,第二個參數必須提供對象上下文。 因此,當第二個參數為this
您的代碼將起作用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.