要使用boost::bind
,你需要做的是设置一个布尔为true的功能,这样你就可以绑定到它:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/ref.hpp>
void make_true(bool& b)
{
b = true;
}
int main()
{
using namespace boost;
bool flag = false;
// without ref, calls with value of flag at the time of binding
// (and therefore would call make_true with a copy of flag, not flag)
function<void()> f = bind(make_true, ref(flag));
f();
assert(flag);
}
然而,拉姆达的帮助在这里。 Lambda就像绑定一样,只是它们的功能也是如此,因此请将代码保存在本地(不需要一些外部函数)。你会做这样的事情:
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
int main()
{
using namespace boost;
using namespace boost::lambda;
bool flag = false;
function<void()> f = (var(flag) = true);
f();
assert(flag);
}
同样的想法,除了bind
和make_true
已经被替换为拉姆达。
请原谅我,但由于您无法使用我之前的帮助,我正在经历高度激动。唉,如果一旦教过鱼,你仍然在寻找鱼贩子,我不会再帮你。 – 2010-08-23 20:00:10
@Noah:克服自己。他正在使用Boost.Lambda,即使他在问题主体中没有这样说,所以告诉他这样做并不是特别有用。 – 2010-08-23 20:18:35
我不经常使用Boost的函数库,但也许你根本不想使用lambda函数。只需编写一个将参数设置为true的传统函数,然后绑定该参数即可。 'void F(int&x){x = true; } boost :: function f = bind(F,flag);'? – 2010-08-23 20:26:21