C ++ 11 std: function and std: bind, stdbind
Std: functionIt is the package of callable objects. Its most important function is to implement delayed calls:
# Include "stdafx. h "# include <iostream> // std: cout # include <functional> // std: functionvoid func (void) {std :: cout <_ FUNCTION _ <std: endl;} class Foo {public: static int foo_func (int a) {std :: cout <_ FUNCTION _ <"(" <a <")->:"; return a ;}}; class Bar {public: int operator () (int a) {std: cout <_ FUNCTION _ <"(" <a <")->:"; return ;}}; int main () {// bind the normal function std: function <void (void)> fr1 = func; fr1 (); // bind the static member function std :: function <int (int)> fr2 = Foo: foo_func; std: cout <fr2 (100) <std: endl; // bind the imitation function Bar; fr2 = bar; std: cout <fr2 (200) <std: endl; return 0 ;}
The above Code defines std: function <int (int)> fr2, so fr2 can represent a type of function with the same return value as the parameter table. It can be seen that fr2 stores the referenced function and can be called in subsequent program processes. This usage is common in actual programming.
Std: bindIt is used to bind callable objects with their parameters. After binding, you can use std: function to save the data and call it when needed:
(1) bind the callable object with its parameters to a function simulation;
(2) Some parameters can be bound.
When binding some parameters, you can use std: placeholders to determine which of the following parameters will be called when a call occurs.
# Include "stdafx. h "# include <iostream> // std: cout # include <functional> // std: functionclass A {public: int I _ = 0; // C ++ 11 allows non-static (non-static) data members to initialize void output (int x, int y) at their declarations (within the class) {std: cout <x <"" <y <std: endl ;}; int main () {A a; // bind A member function, save as the imitation function std: function <void (int, int)> fr = std: bind (& A: output, & a, std: placeholders :: _ 1, std: placeholders: _ 2); // call the member function fr (1, 2); // bind the member variable std :: function <int & (void)> fr2 = std: bind (& A: I _, & a); fr2 () = 100; // assign a value to the member variable std: cout <. I _ <std: endl; return 0 ;}