开发者

c++ generic pointer to (member?) function

开发者 https://www.devze.com 2022-12-30 19:35 出处:网络
I can\'t seem to declare a generic pointer to function. Having these 2 functions to be called: void myfunc1(std::string str)

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 err开发者_StackOverflowors.

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?


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_;
    ...
};
0

精彩评论

暂无评论...
验证码 换一张
取 消