std::bind (C++)

Introduced to me by Kajanan. We see this a lot in ROS2 codebase.

Resources

#serendipity This is kind of like setting the capture clause in a Lambda Function.

In std::bind, the number of the arguments is , when is the number of arguments to the function . i.e.

std::bind(f, arg1, arg2, ..., argN);
  • f: This is the function (or callable) you are binding.
  • arg1, arg2, ..., argN: These are the arguments you are binding to the function. You can use actual values, or placeholders like std::placeholders::_1, std::placeholders::_2, etc., which represent arguments to be provided when the new function is called.
#include <functional>
#include <iostream>
 
void add(int a, int b) {
    std::cout << a + b << std::endl;
}
 
auto boundFunc = std::bind(add, 10, std::placeholders::_1);
boundFunc(5);  // Output: 15

std::bind With Member functions

When you use std::bind to bind a member functions, the first argument to std::bind is the object (this) on which the member function will be called. The placeholders (_1, _2, etc.) refer to the arguments that will be passed to the bound function when it is invoked.

Like this

class HelloWorldSubscriber : public rclcpp::Node {
   public:
    HelloWorldSubscriber() : Node{"minimal_subscriber"} {
        auto subscription = this->create_subscription<std::string>(
            "sub_topic", 10, std::bind(&HelloWorldSubscriber::string_callback, this, std::placeholders::_1));
    }
 
   private:
    void string_callback(std::string& str) {
        std::cout << "Received message: " << str << std::endl;
    }
};