tags:

views:

85

answers:

1

I want to suspend a void() function that sets a stack variable to true. How can I do this?

bool flag = false;
boost::function<void()> f = ...;
f();
assert(flag);

This is, obviously, toy code that demonstrates the problem. My attempt at this, using bind, was bind<void>(_1 = constant(true), flag);, but this yields a compilation error.

+5  A: 

To use boost::bind, you'd need to make a function that sets a boolean to true, so you can bind to it:

#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);
}

However, lambda's will help here. Lambda's are like bind, except they make functions too, so keep your code localized (no need for some external function). You'd do something like this:

#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);
}

Same idea, except bind and make_true has been replaced with a lambda.

GMan
Aaaah, so I was barking down the wrong path, trying to wrap a lambda in `bind`. This is much more elegant, like I imagined it should be. Thanks!
Andres Jaan Tack