[英]Using a boost::bind result as a parameter
I have the following code in which I hook callback functions within ROS to do the // Do my stuff
thing in retSelf()
: 我有以下代码,在其中挂钩了ROS中的回调函数,以// Do my stuff
在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
}
Now, this works fine for calls like : 现在,此方法适用于以下呼叫:
void MyClass::MyCallback(sensor_msgs::Image::ConstPtr img){}
subscribe<sensor_msgs::Image>(&MyClass::MyCallback, this);
However, I have other cases where I want to do something like this: 但是,在其他情况下,我想做这样的事情:
void MyClass::AnotherCallback(sensor_msgs::Image::ConstPtr img, int idx){}
subscribe<sensor_msgs::Image>(boost::bind(&MyClass::AnotherCallback, this, _1, 42));
That is, I wish to also specify an index parameter that the client software knows about but the template doesn't, and I end up in AnotherCallback()
with the 42
value set and my code in retSelf()
executed. 也就是说,我还希望指定一个客户端软件知道但模板不知道的索引参数,最后我进入AnotherCallback()
并设置了42
值,并在retSelf()
执行了我的代码。
Note I have to use boost::bind
and not the standard library as ROS only works with the first kind of binding. 注意我必须使用boost::bind
而不是标准库,因为ROS仅适用于第一种绑定。
boost::bind
returns the "unspecified-type" functional object, which can be implicitly converted to the boost::function
with the appropriate template arguments. boost::bind
返回“未指定类型”功能对象,可以使用适当的模板参数将其隐式转换为boost::function
。 So, in your case the return value of boost::bind(&MyClass::AnotherCallback, this, _1, 42)
can be converted to the boost::function<void(sensor_msgs::Image::ConstPtr)>
: 因此,在您的情况下, 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.