bind function and placeholders in C++

Hello, Learners today we will learn about bind function and placeholders in C++. Sometimes we need to manipulate our defined function according to our needs. if we want to bound some arguments of the function to constant values and leaving other arguments as variables (user input) we need to go to the function and modify it, right? Well but from C++11 onwards, our task has become easier after the introduction of placeholders and bind function. With little modification in the main() function we can achieve the same. Let’s check how?

std::bind

std::bind is a standard function object.  std::bind function behaves as a Functional Adaptor. It returns a function object as an output on taking a function as an input. The Returned output function object is with one or more of the arguments of passed input function bound.

std::placeholders

Placeholder objects [ _1, _2, _3, … ,_n ] are contained in a namespace called placeholders. Here n should be considered a positive integer. These placeholders’ objects are used as arguments of bind() function. And they are stored within the generated function object. Each nth unbound argument replaces the corresponding placeholder (_n) when the function object is called with unbound arguments.

C++ Code: bind function and placeholders

#include<iostream>

//for bind()
#include<functional> 
using namespace std;

// for placeholders
using namespace std::placeholders; 

int calc(int num1, int num2, int num3)
{
    return 2*num1 - num2 + num3;
}

int main()
{
    //first argument of bind function in 
    //the function which we want to manipulate
    auto expn = bind(calc, _1, _2, _3); 

    // expn funtion object with two unbound arguments
    out = expn(3,1,2);
    cout << "output : " << out << endl; 
    return 0;
}
  Output : 7

Output : 7

Here, expn() function internally call the calc() function to perform operation. The number of arguments in the function object is always equal to the number of placeholders in the bind function. Also, the position of placeholder in the bind function determines the value position in the called function object. For example

//placeholder position _2, _1.
//Number of placeholder is two
auto expn = bind(calc, _2, 10, _1);

//Number of arguments is two
out = expn(3,2);
cout << "output : " << out << endl;
Output : -3

First argument of expn(3,2) is stored  to ‘num3’ of calc() function, 10 is assigned to ‘num2’ and the second argument of expn(3,2) is assigned to ‘num1’.

Also read: std::allocator() function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *