代码之家  ›  专栏  ›  技术社区  ›  Andres Jaan Tack

如何使用boost::bind或boost::lambda挂起变量分配?

  •  1
  • Andres Jaan Tack  · 技术社区  · 16 年前

    我想挂起一个void()函数,该函数将堆栈变量设置为true。我该怎么做?

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

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

    1 回复  |  直到 16 年前
        1
  •  7
  •   GManNickG    16 年前

    使用 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。