Search code examples
c++boostcallbackboost-bind

boost bind callback function pointer as a parameter


I am trying to pass a function pointer using 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))
        );
}

I get the following errors:

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 &)'

However, I was able to change to the following, it works fine:

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))
        );
}

Why do I get those errors if I declare the method in the Class class?


Solution

  • When you bind a non-static member function, you need to provide the this pointer that will be used. If you don't want the function associated with a particular instance of Class, you should make the function static.

    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.