【问题标题】:boost bind callback function pointer as a parameterboost绑定回调函数指针作为参数
【发布时间】:2011-11-22 01:27:06
【问题描述】:

我正在尝试使用 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 类中声明方法,为什么会出现这些错误?

【问题讨论】:

    标签: c++ boost callback boost-bind


    【解决方案1】:

    绑定非静态成员函数时,需要提供将要使用的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);
    

    注意:上面的代码 sn-p 不在我的脑海中。不过我觉得是对的。

    【讨论】:

    • 足够接近,但占位符位于未命名的命名空间中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2011-02-04
    相关资源
    最近更新 更多