boost绑定回调函数指针作为参数

时间:2011-11-22 01:27:07

标签: c++ boost callback boost-bind

我正在尝试使用boost :: bind传递函数指针。

void
Class::ThreadFunction(Type(*callbackFunc)(message_type::ptr&))
{
}

boost::shared_ptr<boost::thread>
Class::Init(Type(*callbackFunc)(message_type::ptr&))
{
    return boost::shared_ptr<boost::thread> (
        new boost::thread(boost::bind(&Class::ThreadFunction, callbackFunc))
        );
}

我收到以下错误:

1>C:\dev\sapphire\boost_1_46_1\boost/bind/mem_fn.hpp(362) : warning C4180: qualifier applied to function type has no meaning; ignored
1>C:\dev\sapphire\boost_1_46_1\boost/bind/mem_fn.hpp(333) : error C2296: '->*' : illegal, left operand has type 'Type (__cdecl **)(message_type::ptr &)'

但是,我能够更改为以下内容,它运行正常:

void
ThreadFunction(Type(*callbackFunc)(message_type::ptr&))
{
}

boost::shared_ptr<boost::thread>
Class::Init(Type(*callbackFunc)(message_type::ptr&))
{
    return boost::shared_ptr<boost::thread> (
        new boost::thread(boost::bind(&ThreadFunction, callbackFunc))
        );
}

如果我在Class类中声明方法,为什么会出现这些错误?

2 个答案:

答案 0 :(得分:3)

绑定非静态成员函数时,需要提供将使用的this指针。如果您不希望与Class的特定实例关联的函数,则应将该函数设置为静态。

struct Class {
    void foo(int) { }
    static void bar(int) { }
};

std::bind(&Class::foo, 5); // Illegal, what instance of Class is foo being called
                           // on?

Class myClass;
std::bind(&Class::foo, &myClass, 5); // Legal, foo is being called on myClass.

std::bind(&Class::bar, 5); // Legal, bar is static, so no this pointer is needed.

答案 1 :(得分:2)

因为您还需要绑定Class的实例。阅读Boost documentation

认为你需要这个:

boost::thread(boost::bind(
    &Class::ThreadFunction, &someClassInstance, _1), 
    callbackFunc);

注意:上面的代码片段不在我的脑海中。我认为这是正确的。

相关问题