C ++ 11/14 Learning (9) function object wrapper, 14 Functions
Std: function
Lambda expressions are essentially function objects.
When the capture list of a Lambda expression is empty, the Lambda expression can also be passed as a function pointer, for example:
# Include <iostream> Usingfoo = void (int); // defines the function pointer. for usage of using, see alias syntax in the previous section. Voidfunctional (foof ){ F (1 ); } Intmain (){ Autof = [] (intvalue ){ Std: cout <value <std: endl; }; Functional (f); // function pointer call F (1); // lambda expression call Return 0; } |
The above Code provides two different calling methods:
These concepts are unified in C ++ 11, and the types of objects that can be called are called callable types, which are introduced through std: function.
C ++ 11 std: function is a universal, multi-state function encapsulation that can store, copy, and call any callable target object.
It is also a type-safe package for the existing callable entities in C ++ (relatively speaking, function pointer calls are not type-safe), in other words, it is the function container.
When we have a function container, we can more easily process functions and function pointers as objects.
For example:
# Include <functional> # Include <iostream> Intfoo (intpara ){ Returnpara; } Intmain (){ // Std: function encapsulates a function whose return value is int and its parameter is int. Std: function <int (int)> func = foo; Intimpant ant = 10; Std: function <int (int)> func2 = [&] (intvalue)-> int { Return 1 + value + important; }; Std: cout <func (10) <std: endl; Std: cout <func2 (10) <std: endl; } |
Std: bind/std: placeholder
Std: bind is used to bind function call parameters. It solves the following problems:
Sometimes we may not be able to obtain all the parameters that call a function at a time.
Through this function, we can bind some call parameters to the function in advance to form a new object, and then complete the call after the parameters are complete.
For example:
Intfoo (inta, intb, intc ){ ; } Intmain (){ // Bind parameter 1 and 2 to function foo, // But use std: placeholders: _ 1 to placeholder the first parameter. AutobindFoo = std: bind (foo, std: placeholders: _ 1, 1, 2 ); // When calling bindFoo, you only need to provide the first parameter. BindFoo (1 ); } |