Function/bind:
std::function:? std::function<r (T1, T2, ..., TN) >
? This is a template implementation of thefunction Object class, it canPackagingAny of the otherFunction Object, and the wrapped function object has a parameter of type T1,t2,..., TN whose return value is R type
The greatest use of a function object is to implementfunction Callback
bind: ? Bind is a mechanism that can pre- bind Some parameters of a specified callable entity to an existing variable, resulting in a new callable entity? The number of parameters to bind is not limited, and the specific parameters of the binding are not restricted. specified by the user? Bind pre-bound parameters need to pass specific variables or values in , is pass-by-value (value transfer) ? For parameters that are not bound in advance, STD is required::p laceholders Go in, start from _1 , increment in turn? The return value of BIND is a callable entity and can be assigned directly to the Std::function object
Object-oriented vs Object-based:? The three main features of object-oriented (encapsulation, inheritance, polymorphism) are indispensable.? "Object-based" is usually used for objects, but does not take advantage of existing object templates to produce new object types, resulting in new objects,"Object-based" does not inheritThe characteristics of the.? " Object-oriented "and" Object-based ""Encapsulation" is implemented.The concept, butObject OrientedImplementation of the "Inheritance and polymorphism", and" object-based "did not implement these.
Inheritance (object-oriented) vs combination (Object-based)
//Bind returns a new callable entity //Function object implementation callback #include <iostream> #include <functional> using namespace std; using Std::function; //using std::p laceholders; Namespace ' std::p laceholders ' not allowed in using-declaration using namespace std::p laceholders; int func (int x,int y) { return x+y; } class A { Public : int func (int x,int y) { return x+y; } }; |
int main () { //Function<int (int,int) > test1 = bind (func,10,placeholders::_1); ///Only one placeholder, meaning that the parameter can only be passed one, so the parameter cannot be two, and the original function is OK function<int (int) > Test1 = bind (func,10,placeholders::_1); Cout<<test1 (<<endl;) A; function<int (int) > Test2 = bind (&a::func,&a,30,_1); //Before declaring, you don't have to write placeholders cout<<test2 (<<endl;) function<int (int,int) > Test3 = func; cout<<test3 (10,20) <<endl; //function<int (const a&,int,int) > test4 = &A::func; function<int (a&,int,int) > test4 = &A::func; //Today's brain is a sucker, const member objects can only call const-decorated member functions cout<<test4 (a,10,20) <<endl; return 0; } |
C++11 new features, bind, Object-based