使用boost ::绑定结果作为参数

Using a boost::bind result as a parameter

本文关键字:参数 绑定 boost 使用 结果      更新时间:2023-10-16

我有以下代码,其中我在ROS中挂接回调功能以在retSelf()中执行// Do my stuff的事情:

template <typename T>
const typename T::ConstPtr retSelf(const typename T::ConstPtr self, size_t id)
{
    // Do my stuff
    return self;
}
template<typename CallbackType, typename ClassType>
void subscribe(void (ClassType::*cb)(typename CallbackType::ConstPtr const),
               ClassType *thisPtr)
{
    auto id = generateId(...);
    auto selfP = &retSelf<CallbackType>;
    auto returnSelf = boost::bind(selfP, _1, id);
    auto callback = boost::bind(cb, thisPtr, returnSelf);
   // Register callback
}

现在,这适用于以下电话:

void MyClass::MyCallback(sensor_msgs::Image::ConstPtr img){}
subscribe<sensor_msgs::Image>(&MyClass::MyCallback, this);

但是,我还有其他情况我想做这样的事情:

void MyClass::AnotherCallback(sensor_msgs::Image::ConstPtr img, int idx){}
subscribe<sensor_msgs::Image>(boost::bind(&MyClass::AnotherCallback, this, _1, 42));

也就是说,我还希望指定客户端软件所知道的索引参数,但模板却没有,我最终以AnotherCallback()42值集和我的代码在retSelf()中执行。

注意,我必须使用boost::bind,而不是标准库,因为ROS仅适用于第一种绑定。

boost::bind返回"未指定型"功能对象,可以将其隐式转换为使用适当的模板参数的boost::function。因此,在您的情况下,boost::bind(&MyClass::AnotherCallback, this, _1, 42)的返回值可以转换为boost::function<void(sensor_msgs::Image::ConstPtr)>

using callback_t = boost::function<void(sensor_msgs::Image::ConstPtr)>;
void subscribe(const callback_t &callback) {
    // register callback
}
// ...
subscribe(boost::bind(&MyClass::AnotherCallback, this, _1, 42));