gpt4 book ai didi

c++ - 使用 boost::bind 结果作为参数

转载 作者:行者123 更新时间:2023-11-28 04:23:54 26 4
gpt4 key购买 nike

我有以下代码,我在 ROS 中 Hook 回调函数。在 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 仅适用于第一种绑定(bind)。

最佳答案

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

关于c++ - 使用 boost::bind 结果作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com