boost :: bind()使用对象指针作为占位符的boost :: function的成员函数?

时间:2013-09-16 21:07:52

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

我在MSVC7上使用boost v1.37。我坚持使用这些旧版本,无法升级,所以请帮助我在这里工作,不建议升级作为答案。

我有一个有三个成员函数的类。我想定义一个boost::function,可用于在同一个类的不同实例上调用不同的成员函数:

typedef boost::function<bool (unsigned, unsigned)> MyFunc;

绑定看起来像:

boost::bind( &A::foo1, _1, _2, _3, boost::ref(some_fixed_param) );

我需要将上面的boost::bind传递给一个以MyFunc作为参数的函数。

如何设置boost::function以获取将实例对象设置为占位符的函数对象(来自boost::bind)?如何将实例(this)传递到boost::function?我一直在这里遇到编译器错误,所以只是试图确保我理解正确。希望我已经清楚地解释过了。提前谢谢。

修改

我得到的真正错误是:

sample.cpp(1156) : error C2664: 'process' : cannot convert parameter 2 from 'boost::_bi::bind_t<R,F,L>' to 'FooFunc &'
        with
        [
            R=bool,
            F=boost::_mfi::mf3<bool,A,unsigned int,unsigned int,int>,
            L=boost::_bi::list4<boost::arg<1>,boost::arg<2>,boost::arg<3>,boost::reference_wrapper<int>>
        ]

我正在使用的代码:

typedef boost::function<bool (unsigned, unsigned)> FooFunc;

class A
{
public:
    bool foo1( unsigned s1, unsigned s2, int s3 )
    {
    }
};

bool process( unsigned s1, FooFunc& foo )
{
    unsigned s2 = 100;
    A* a; // pretend this is valid
    return foo( s1, s2 );
}

void dostuff()
{
    int s3 = 300;

    process( 200,
        boost::bind( &A::foo1, _1, _2, _3, boost::ref( s3 ) ) );
}

现在我知道这不是有效的代码,因为在process()函数中,我需要使用实例指针foo来调用a。不知道如何连接两者并且不确定编译器错误发生的原因。

1 个答案:

答案 0 :(得分:3)

首先,您需要将类的引用添加到boost :: function的签名中:

typedef boost::function<bool (A *, unsigned, unsigned)> FooFunc;

这确实要求在此typedef之前声明A类。然后,在您的process函数中,您可以在调用给定的FooFunc时提供此引用

bool process( unsigned s1, FooFunc foo )
{
    unsigned s2 = 100;
    A* a = 0; // pretend this is valid
    return foo( a, s1, s2 );
}

请注意,我还将对FooFunc的非const引用更改为值参数。其余代码将按原样运行。

我无法访问MSVC7(我真的希望你有7.1而不是7.0)。您可能需要使用boost.function文档中描述的“可移植语法”,例如:

typedef boost::function<bool , A *, unsigned, unsigned> FooFunc;
相关问题