【问题标题】:Using a boost::bind result as a parameter使用 boost::bind 结果作为参数
【发布时间】:2019-02-25 07:49:05
【问题描述】:

我有以下代码,其中我在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'ed 回调传递给函数。 boost::bind 返回一个 boost::function&lt;FUNCTION_SIGNATURE&gt; 类型的函数对象,在您的情况下,FUNCTION_SIGNATURE 应该是 void(sensor_msgs::Image::ConstPtr)。因此,您可以创建一个接受 boost::function 作为参数的方法,例如:void subscribe(const boost::function&lt;void(sensor_msgs::Image::ConstPtr)&gt; &amp;cb);
  • 啊,boost::function 是我遗漏的部分 - 我找不到对 boost::bind 的返回类型的引用。请您将其发布为答案吗?

标签: c++ c++11 templates boost


【解决方案1】:

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

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多