Tag: Bind adapter Function Binding
C + + supplements--bind function binding
Preface
The BIND function binds a fixed parameter to a known function to form a new function, thereby reducing the number of arguments and reducing the difficulty of calling the function. It should be noted that Bind is a function adapter.
bind function
Instance
#include <iostream> #include <functional>using namespace std;using namespace std::p laceholders;int Main () { Auto fun = [] (int *array, int n, int. num) {for (int i = 0; i < n; i++) {if (array[i] > num) cout << Array[i] < < ends;} cout << Endl;}; int array[] = {1, 3, 5, 7, 9};//_1,_2 is a placeholder for auto FUN1 = bind (fun, _1, _2, 5);//equivalent to calling fun (array, sizeof (array)/sizeof (*arr ay), 5); fun1 (array, sizeof (array)/sizeof (*array)); Cin.get (); return 0;}
Run
7 9
The example is very simple and everyone can understand it at a glance. But it is necessary to explain:
1. What is an adapter?
Adapters are a mechanism to change what you already have, to change it, to limit it, and to adapt it to new logic. It should be noted that containers, iterators, and functions all have adapters.
Bind is a function adapter that accepts a callable object and generates a new callable object to accommodate the original object's argument list.
General form of BIND use:
- Auto Newfun = bind (fun, arg_list);
where fun is a function, arg_list is a comma-separated list of arguments. Call Newfun (), Newfun will call Fun (arg_list);
2._1,_2 is a placeholder, defined in the namespace placeholders. _1 is the first parameter of Newfun, _2 is the second parameter of Newfun, and so on.
By the way, what are the placeholder parameters?
int fun (int A, int b, int) {return a + B;}
The call style is similar to Fun (1, 2, 0);
This fun function design is interesting, it accepts three int parameters, but the third parameter does not give the variable name, so that the function body can not use the parameter, since it has been designed, but not? What does that mean?
This is the placeholder parameter, which provides a reserved interface for the upgrade of the function.
Directory of all content
C + + supplements--bind function binding