2

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?

pandarulez
  • 91
  • 11
  • What do you mean by "as an optimization"? `std::bind` and lambdas are just two different syntaxes leading to the same functionality. –  Oct 14 '21 at 18:52
  • I found couple of resources stating bind shouldn't be used https://abseil.io/tips/108 – pandarulez Oct 14 '21 at 18:55
  • While I agree that any talk of optimization requires a "perf or it didn't happen", @Frank, I think it's fair to say lambdas are slightly more susceptible to inling. – StoryTeller - Unslander Monica Oct 14 '21 at 18:56
  • @SumeshThakur - There are many good reasons in that article, but none of them are to do with optimization. If your code works as is, and it doesn't solve any problem, don't fix it. The guideline is about new code. – StoryTeller - Unslander Monica Oct 14 '21 at 18:58

3 Answers3

4

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); }
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
4

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); }
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
2

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);
        })},
pandarulez
  • 91
  • 11