Home > Software engineering >  How to use lambda intead of std::bind in create_subscription method in ROS2
How to use lambda intead of std::bind in create_subscription method in ROS2

Time:10-15

I am creating a small euclidean clustering node for the point cloud, utilizing PCL's implementation of the KD tree.

Currently, my subscriber definition looks like this,

ClusteringNode::ClusteringNode(const rclcpp::NodeOptions &options)
      : Node("clustering_node", options),
        cloud_subscriber_{create_subscription<PointCloudMsg>(
            "input_cloud", 10,
            std::bind(&ClusteringNode::callback, this,
                      std::placeholders::_1))},

the definition of KD-tree method is inside callback method and is working perfectly,

Now just to improve it furthur, I want to use lambdas instead of the std::bind function here,

What should be the approach here?

CodePudding user response:

The std::bind() statement:

std::bind(&ClusteringNode::callback, this, std::placeholders::_1)

Would translate into a lambda like this:

[this](const auto msg){ callback(msg); }

Or, if the callback() has a non-void return value:

[this](const auto msg){ return callback(msg); }

CodePudding user response:

You can replace

std::bind(&ClusteringNode::callback, this, std::placeholders::_1)

with

[this](auto&& var){ return callback(std::forward<decltype(var)>(var)); }
// or if no return value
[this](auto&& var){ callback(std::forward<decltype(var)>(var)); }

If you don't need to support perfect forwarding, it can be shortened to

[this](const auto& var){ return callback(var); }
// or if no return value
[this](const auto& var){ callback(var); }

CodePudding user response:

This worked for me,

ClusteringNode::ClusteringNode(const rclcpp::NodeOptions &options)
  : Node("clustering_node", options),
    cloud_subscriber_{create_subscription<PointCloudMsg>(
        "input_cloud", 10,
        [this] (const PointCloudMsg::SharedPtr msg){
          callback(msg);
        })},
  • Related