I want to be able to define a callback through a lambda but I can't get any of the function signatures to match.
std::function<void(const sensor_msgs::PointCloud2)> callback =
[&mycapture](const sensor_msgs::PointCloud2 msg) {
// do something with msg and capture
};
auto sub = ros_node.subscribe("/sometopic", 1, callback)
I can't get this to work as subscribe wants a function pointer. Is what I'm trying to do possible with ROS? That is, can I pass into the subscribe method a lambda with a capture?
I have hit this issue as well in Melodic. While solution with explicit cast to boost function worked, it was very verbose. Under the hood, this solution boils to forcing compiler to choose the last overload of node_handle::subscribe
that takes two template arguments:
* \param M [template] the message type
* \param C [template] the callback parameter type (e.g. const boost::shared_ptr<M const>& or const M&)
template<class M, class C>
Subscriber subscribe(const std::string& topic, uint32_t queue_size, const boost::function<void (C)>& callback
Because it is the only overload that has two template arguments, it can be enforced by specifying those parameters explicitly.
In specifics of the question asked, adding a subscriber will look like this (C++14):
ros::Subscriber subscriber = nh.subscribe<sensor_msgs::PointCloud2, const sensor_msgs::PointCloud2&>(topic, 1, [&mycapture](auto msg) {
mycapture.workWith(msg.data);
});
I was able to get this working with capture.
T obj;
boost::function<void (const sensor_msgs::PointCloud2&)> callback =
[obj] (const sensor_msgs::PointCloud2& msg) {
// Do something here
}
auto sub = ros_nh.subscribe<sensor_msgs::PointCloud>(topic, 1, callback);
ROS Version: Indigo
C++14
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With