简体   繁体   English

使用boost :: bind和boost :: function将成员函数分配给回调

[英]Assigning member function to callback with boost::bind and boost::function

I am trying to assign a member function as the callback to an API method, but it return the below error message, I am not sure how to resolve this. 我正在尝试将成员函数分配为API方法的回调,但是它返回以下错误消息,我不确定如何解决此问题。

cannot convert ‘boost::function<int(rcv_t_stct*, msg_t_stct*)>*’ to ‘rcv_cb {aka int (*)(rcv_t_stct*, msg_t_stct*)}’

callback signature: 回调签名:

typedef int (*rcv_cb)(rcv_t *rcv, msg_t *msg);

callback setter: 回调设置器:

create(rcv_cb cb);

my member function: 我的会员功能:

int receiver::on_received(rcv_t *rcv, msg_t *msg)
{
    return 0;
}

attempted to assign to the setter: 尝试分配给设置者:

boost::function<int (rcv_t *, msg_t *)> f2( boost::bind( &receiver::on_received, this, _1, _2) ); 
create(f2);

Solution: 解:

I changed the receiver class to singleton, and used a static member function to wrap the non-static one. 我将接收器类更改为单例,并使用静态成员函数包装非静态函数。

int receiver::on_received(rcv_t *rcv, msg_t *msg)
{
    return receiver::instance().on_received_private(rcv, msg);
}

Is this the best solution it can be to resolve this issue? 这是解决此问题的最佳解决方案吗?

A boost::function<> is not a free function, but a functor (type implementing operator() ). boost::function<>不是自由函数,而是函子(类型为operator()实现)。 You cannot convert from boost::function<S> to a pointer to a function with the signature S . 您不能将boost::function<S>转换为带有签名S的函数的指针。 If it is within your control, you can change the callback setter to take a boost::function<> rather than a free function. 如果它在您的控制之内,则可以更改回调设置器以使用boost::function<>而不是自由函数。 If that is outside of your control, then you cannot use a non-static member function for the callback. 如果那不在您的控制范围内,则您不能将非静态成员函数用于回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM