2010-08-23 96 views
1

我想暂停一个将stack变量设置为true的void()函数。我怎样才能做到这一点?如何暂停使用boost :: bind或boost :: lambda进行变量赋值?

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

很明显,这是玩具代码,它演示了这个问题。我在此尝试使用bind,是bind<void>(_1 = constant(true), flag);,但这会产生编译错误。

+0

请原谅我,但由于您无法使用我之前的帮助,我正在经历高度激动。唉,如果一旦教过鱼,你仍然在寻找鱼贩子,我不会再帮你。 – 2010-08-23 20:00:10

+2

@Noah:克服自己。他正在使用Boost.Lambda,即使他在问题主体中没有这样说,所以告诉他这样做并不是特别有用。 – 2010-08-23 20:18:35

+1

我不经常使用Boost的函数库,但也许你根本不想使用lambda函数。只需编写一个将参数设置为true的传统函数,然后绑定该参数即可。 'void F(int&x){x = true; } boost :: function f = bind(F,flag);'? – 2010-08-23 20:26:21

回答

7

要使用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); 
} 

同样的想法,除了bindmake_true已经被替换为拉姆达。

+0

Aaaah,所以我吠叫了错误的路径,试图在'bind'中包装一个lambda。这更优雅,就像我想象的那样。谢谢! – 2010-08-24 00:15:22

相关问题