#include <iostream>#include<functional>#include<vector>using namespacestd;//C type global functionintC_func (intAintb) { returnA +b;}//Function Objectclassfunctor{ Public: int operator() (intAintb) {returnA +b; }};intMain () {// Old Use-typedefint(*f) (int,int); F F=C_func; cout<<f (1,2) <<Endl; Functor ft; cout<<ft (1,2) <<Endl; /////////////////////////////////////////////std::function<int(int,int) >MyFunc; MyFunc=C_func; cout<<myfunc (3,4) <<Endl; MyFunc=ft; cout<<myfunc (3,4) <<Endl; //LambdaMyFunc = [] (intAintb) {returnA +b;}; cout<<myfunc (3,4) <<Endl; //////////////////////////////////////////////std::vector<std::function<int(int,int) > >v; V.push_back (C_func); V.push_back (FT); V.push_back ([] (intAintb) {returnA +b;}); for(Constauto&e:v) {cout<<e (Ten,Ten) <<Endl; } return 0;}
In C + +, callable entities mainly include functions, function pointers, function references, objects that can be implicitly converted to functions specified by the function, or objects that implement Opetator () (that is, functorin c++98). In C++11, a new Std::function object is added, and the Std::function object is a type-safe package for existing callable entities in C + + (we know that such callable entities as function pointers are unsafe types).
- (1) The following two principles apply to the conversion of callable entities to std::function objects:
A. Parameters of the converted Std::function object can be converted to the parameters of the callable entity
B. The return value of the callable entity can be converted to the return value of the Std::function object (note here that the return value of all callable entities is compatible with the return value of the Std::function object that returns void).
- (2) Std::function object can refer to satisfy any callable entity of the condition in (1)
- (3) The greatest use of std::function object is to implement a function callback, and the user needs to be aware that it cannot be used to check for equality or inequality.
c++11 function