C ++ generic function pointer (member?)

I am unable to declare a generic function pointer.

With these two functions:

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 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 a member function they give me compilation errors.

it works:

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

      

this is not true:

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

      

How should this be done?

+2


a source to share


1 answer


boost::bind

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

:



struct example
{
    boost::function<void(std::string)> userhandler_;
    ...
};

      

+7


a source







All Articles