std::placeholders (C++)

The std::placeholders namespace contains the placeholder objects [_1, ..., _N] where N is an implementation defined maximum number.

Resources

std::placeholders are used in conjunction with std::bind to create partially applied functions.

Example

#include <iostream>
#include <functional>
 
void add(int a, int b) {
    std::cout << "Sum: " << a + b << std::endl;
}
 
int main() {
    // Bind the second argument as a placeholder (_1)
    auto add_with_first_arg_fixed = std::bind(add, 5, std::placeholders::_1);
 
    // Calling the bound function with the second argument
    add_with_first_arg_fixed(10);  // Output: Sum: 15
 
    return 0;
}
 
#include <iostream>
#include <functional>
 
void multiply(int a, int b, int c) {
    std::cout << "Result: " << a * b * c << std::endl;
}
 
int main() {
    // Reordering arguments: here, _2 will be passed to the first argument of multiply,
    // _1 to the second argument, and 3 is fixed as the third argument.
    auto reorderedMultiply = std::bind(multiply, std::placeholders::_2, std::placeholders::_1, 3);
 
    // Call the reordered function
    reorderedMultiply(4, 5);  // Output: Result: 60 (i.e., 5 * 4 * 3)
 
    return 0;
}
 

Here, boundFunc is this function

 
void myFunction(int x, int y) {
    return;
}
 
std::function<void(int)> boundFunc = std::bind(myFunction, 10, std::placeholders::_1);

We see this a lot in ROS, when you bind the first value to this.