【问题标题】:Using boost::function and boost::bind to a member variable使用 boost::function 和 boost::bind 到成员变量
【发布时间】:2012-09-27 01:36:12
【问题描述】:

我正在尝试创建一个允许设置对象成员变量的 boost::function。我创建了一个我能想到的最简单的例子来了解我正在尝试(和失败)做的事情。我觉得我掌握了 boost::bind,但我是 boost 新手,我相信我使用 boost::function 不正确。

#include <iostream>
#include <Boost/bind.hpp>
#include <boost/function.hpp>

class Foo
{
public:
    Foo() : value(0) {}

    boost::function<void (int&)> getFcn()
    {
        return boost::function<void (int&)>( boost::bind<void>( Foo::value, this, _1 ) );
    }

    int getValue() const    { return value; }

private:
    int value;
};

int main(int argc, const char * argv[])
{
    Foo foo;

    std::cout << "Value before: " << foo.getValue();

    boost::function<void (int&)> setter = foo.getFcn();
    setter(10);     // ERROR: No matching function for call to object of type 'boost::function<void (int &)>'
                    // and in bind.hpp: Called object type 'int' is not a function or function pointer

    std::cout << "Value after: " << foo.getValue();

    return 0;
}

我在第 28 行遇到错误,我想使用该函数将 Foo::value 设置为 10。我只是在处理这整件事错了吗?我应该只传回一个 int* 或其他东西,而不是使用 boost 来完成所有这些吗?我之所以调用“getFcn()”是因为在我的实际项目中我使用的是消息传递系统,如果包含我想要的数据的对象不再存在,getFcn 将返回一个空的 boost::function。但我想如果没有找到任何东西,我可以使用 int* 返回 NULL。

【问题讨论】:

    标签: c++ boost function-pointers boost-bind boost-function


    【解决方案1】:

    您代码中的这个boost::bind&lt;void&gt;( Foo::value, this, _1 ) 本质上是使用Foo::value 作为成员函数。这是错误的。 Foo::value 不是函数。

    让我们一步一步构建:

    class Foo
    {
        ...
        boost::function< void (Foo*, int) > getFcn ()
        {
            return boost::function< void (Foo*, int) >( &Foo::setValue );
        }
    
        void setValue (int v)
        {
            value = v;
        }
        ...
    }
    
    int main ()
    {
        ...
        boost::function< void (Foo*, int) > setter = foo.getFcn();
        setter( &foo, 10);
        ...
    }
    

    所以这里函数显式地采用this 对象。让我们使用boost.bind 绑定this 作为第一个参数。

    class Foo
    {
        ...
        boost::function< void (int) > getFcn ()
        {
            return boost::bind(&Foo::setValue, this, _1);
        }
    
        void setValue (int v)
        {
            value = v;
        }
        ...
    }
    
    int main ()
    {
        ...
        boost::function< void (int) > setter = foo.getFcn();
        setter( 10);
        ...
    }
    

    (未经测试的代码)

    【讨论】:

    • 我试图避免在类中为我想要执行此操作的每个变量设置一个 setter 方法。我正在寻找一种直接更改变量的方法。 boost::function 不能那样用吗?
    • @NicFoster,我相信不会。 Boost.Function 是对行为类似函数的事物的封装。您正在尝试将其包裹在 int.
    • 很公平,我认为既然您可以使用 bind 绑定到成员变量,那么您将能够使用 function 来设置这些成员变量。
    猜你喜欢
    • 2016-03-16
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多