【问题标题】:boost::bind help for callback with member functionboost::bind 对成员函数回调的帮助
【发布时间】:2012-11-28 20:35:01
【问题描述】:

您好,我是一名学生,正在开发一个使用成员函数回调的程序。我遇到了 bind 的使用,这正是我所需要的。我只是很难让它工作。

下面是相关代码和编译错误

 // 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*))’

有人可以帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: c++ boost callback boost-bind


    【解决方案1】:

    首先,我很惊讶您没有收到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*,它们是不同的名称。我不知道这是否会成为问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 2015-06-15
      • 2013-11-12
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多