boost::使用成员函数绑定回调的帮助

boost::bind help for callback with member function

本文关键字:回调 帮助 绑定 成员 boost 函数      更新时间:2023-10-16

你好,我是一名学生,正在编写一个使用成员函数回调的程序。我偶然发现了绑定的用法,这正是我所需要的。我只是很难让它发挥作用。

以下是的相关代码和编译错误

// this is the API function to register callback
void register_callback_datapoint(void(*)(datapoint_t *datapoint) cb_datapoint ) 
// this function is my callback
void datapoint_update(datapoint_t* datapoint);
// this code is called in the aggregateThread class
boost::function<void(datapoint_t*)> f;
f = bind(&aggregateThread::datapoint_update, this, std::tr1::placeholders::_1);
register_callback_datapoint(f);
// here is the compile error
cannot convert ‘boost::function<void(datapoint_opaque_t*)>’ to ‘void (*)(datapoint_t*)
{aka void (*)(datapoint_opaque_t*)}’ for argument ‘1’ to ‘void 
register_callback_datapoint(void (*)(datapoint_t*))’

有人能帮我做这个吗?谢谢

首先,我很惊讶您没有收到void register_callback_datapoint(void(*)(datapoint_t *datapoint) cb_datapoint )的错误。正确的语法应该是void register_callback_datapoint(void(*cb_datapoint)(datapoint_t *datapoint));,用于声明函数指针作为参数。

但是,问题是您试图传递一个boost::function,它是一个函数对象,不能隐式转换为指向register_callback_datapoint的函数指针。您需要将参数更改为boost::function或使其成为模板。

void register_callback_datapoint(boost::function<void(datapoint_opaque_t*)> f);

template <typename Func>
void register_callback_datapoint(Func f);

此外,我刚刚注意到这一点,但您的示例和编译错误不匹配。一个说datapoint_opaque_t*,另一个说是datapoint_t*,它们是不同的名称。我不知道这是否会成为一个问题。