views:

148

answers:

1

I can't seem to declare a generic pointer to function.

Having these 2 functions to be called:

void myfunc1(std::string str)
{
    std::cout << str << std::endl;
}
struct X
{
        void f(std::string str){ std::cout<< str << std::endl;}
};

and these two function callers:

typedef void (*userhandler_t) (std::string);
struct example
{   
    userhandler_t userhandler_;

    example(userhandler_t userhandler): userhandler_(userhandler){}

    void call(std::string str)
    {   
        userhandler_(str);
    }
};
template<typename func_t>
void justfunc(func_t func)
{
    func("hello, works!");
}

when I try to use them with boost::bind to call the member function they give me compile errors.

this works:

example e1(&myfunc1);
e1.call("hello, world!");
justfunc(&myfunc1);

this doesn't:

X x;
example e2(boost::bind(&X::f, &x, _1));
e2.call("hello, world2!");
justfunc(boost::bind(&X::f, &x, _1));

How is this supposed to be done?

+7  A: 

boost::bind creates objects that behave like functions, not actual function pointers. Use the Boost.Function library to hold the result of calling boost::bind:

struct example
{
    boost::function<void(std::string)> userhandler_;
    ...
};
Marcelo Cantos
As Marcelo said, `boost::bind` creates __function objects__ (aka _functors_), not _function pointers_. +1 from me.
sbi
Thx, I missed that in the docs (was here: http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html#with_boost_function)
João Portela