使用
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在这里有帮助。lambda类似于bind,只是它们也使函数成为可能,所以请将代码本地化(不需要某些外部函数)。你可以这样做:
#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
已替换为lambda。