使用boost ::绑定结果作为参数
Using a boost::bind result as a parameter
我有以下代码,其中我在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));
相关文章:
- 为什么 std::绑定错误参数可以成功?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 绑定到可变参数成员函数
- 如何在 C# 中将带有参数的函数绑定到包中
- 如何将参数绑定到构造函数?
- C++ 如何将参数绑定到具有相同返回类型的函数,并将它们全部存储在一个容器中
- 函数参数绑定通过参考与传递指针传递数组的规则
- C 如何将参数绑定到接受函数的函数
- 模板参数绑定
- 是由BOOST ::返回的函子,仅使用绑定的参数绑定,等效于不采用参数的函数
- 当常量引用参数绑定到右值时,右值是否保持其"status"?
- 用emscripten中的参考参数绑定函数
- 如何将Boost ::函数对象与所有参数绑定
- std ::将参数绑定到没有对象的情况下的成员函数
- 隐马尔可夫模型-在C++中实现参数绑定
- 函数参数绑定的完美转发和歧义
- 为容器中的每个对象调用具有一个参数(绑定)的成员函数
- std::bind():将lambda与右值引用作为参数绑定
- 与派生函数参数绑定
- 与模板模板类一起使用的自定义模板参数绑定器