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