C++11 bind function

Keywords: Programming

The Use of Bid Function

You can think of a bind function as a general function adapter that accepts a callable object and generates a new callable object to "fit" the parameter list of the original object.
The general form of calling bind: auto newCallable = bind(callable,arg_list);`

newCallable itself is a callable object, and arg_list is a comma-separated parameter list corresponding to a given callable parameter. That is, when we call the new Callable, the new Callable calls the callable and passes it the parameters in arg_list.

The parameters in arg_list may contain names like _n, where n is an integer, and these parameters are placeholders, representing the parameters of the new Callable, which occupy the "position" of the parameters passed to the new Callable. The value n denotes the position of the parameters in the generated callable object: _1 is the first parameter of the new Callable, and _2 is the second parameter, and so on.

1. Binding Common Functions

#include<iostream>
#include<functional>
using namespace std;

int plus(int a,int b)
{
   return a+b;
}
int main()
{
  //Represents that the binding function plus parameters are specified by the first and second parameters calling func1, respectively.
   function<int<int,int>> func1 = std::bind(plus, placeholders::_1, placeholders::_2);
   
  //The type of func2 is function < void (int, int), int > the same as func1
   auto  func2 = std::bind(plus,1,2);   //Represents the first and second of the binding function plus: 1, 2 
   cout<<func1(1,2)<<endl; //3
   cout<<func2()<<endl; //3
   retunrn 0;
}

2. Membership functions of bound classes

#include<iostream>
#include<functional>
using namespace std;
class Plus
{
   public:
   	int plus(int a,int b)
   	{
   	    return a+b;
   	}
}
int main()
{
   Plus p;
   // Calling member functions in pointer form
   function<int<int,int>> func1 = std::bind(&Plus::plus,&p, placeholders::_1, placeholders::_2);
  // Calling member functions in object form
   function<int<int,int>> func2 = std::bind(&Plus::plus,p, placeholders::_1, placeholders::_2);
   cout<<func1(1,2)<<endl; //3
   cout<<func2(1,2)<<endl; //3
   retunrn 0;
}

The placeholder_1 is in the namespace of placeholders, while placeholders are in the namespace of std.

3. Binding class static member functions

#include<iostream>
#include<functional>
using namespace std;
class Plus
{
	public:
		static int plus(int a,int b)
		{
		    return a+b;
		}
}
int main()
{
   function<int<int,int>> func1 = std::bind(&Plus::plus, placeholders::_1, placeholders::_2);
   cout<<func1(1,2)<<endl; //3
   retunrn 0;
}

Reference: primer C++ 5th Edition

Posted by psycho_somatic on Sat, 26 Jan 2019 05:57:14 -0800