From a function pointer to an imitation function.
The 1.1 function call operator (left and right brackets in the C + + syntax) can also be overloaded.
Many STL algorithms are available in two versions, one for general conditions (such as when sorting in ascending order), and one for special conditions (such as when sorting by the user to specify what special relationship to arrange). In this case, a user is required to specify a condition or policy, and a condition or policy is made up of a whole set of actions that require something special to represent this "whole set of actions."
Representing "a whole set of operations," is a function. In the old-fashioned C language, to pass a function as an argument, only through a function pointer. Examples are as follows:
#include <cstdlib>#include<iostream>using namespacestd;intFCMP (Const void* Elem1,Const void*elem2);intMain () {intia[Ten] = { +, the, +, A, +, -, the, -, Wu,9}; for(intI=0; i<Ten; i++) cout<< Ia[i] <<" "; cout<<Endl; Qsort (IA,sizeof(IA)/sizeof(int),sizeof(int), fcmp); for(intI=0; i<Ten; i++) cout<< Ia[i] <<" "; return 0;}intFCMP (Const void* Elem1,Const void*elem2) { Const int* I1 = (Const int*) elem1; Const int* I2 = (Const int*) elem2; if(*i1 < *i2)return-1; Else if(*i1 = = *i2)return 0; Else if(*i1 > *i2)return 1; }
The disadvantage of a function pointer is that it cannot hold its own state (local state), nor can it achieve adaptability in component technology-that is, it is no longer possible to add certain modifiers to it and change its state.
1.2 For this reason, the concept of affine function is introduced. The so-called "conditional" or "policy" or "whole set of operations" accepted by the special version of the STL algorithm are presented in the form of an imitation function.
The operator () overload for a class becomes an imitation function.
Examples are as follows:
1#include <iostream>2 using namespacestd;3 4 //because the operator () is overloaded, plus becomes an imitation function5Template <classT>6 structPLUS {7Toperator() (Constt& x,Constt& y)Const{returnX +y;}8 };9 Ten //because the operator () is overloaded, minus becomes an imitation function OneTemplate <classT> A structminus { -Toperator() (Constt& x,Constt& y)Const{returnX-y;} - }; the - intMain () { - //generating an imitation function object -plus<int>plusobj; +minus<int>minusobj; - + //use a functor, just as you would with a generic function Acout << Plusobj (3,5) <<Endl; atcout << Minusobj (3,5) << Endl <<Endl; - - //a temporary object that directly produces a functor (first pair of parentheses) and calls (second pair of parentheses) -cout << plus<int> () (7,6) <<Endl; -cout << minus<int> () (7,6) <<Endl; -}
The above plus<t> and minus<t> have been very close to the implementation of STL, the only difference is that it lacks "adaptable ability".
1.3 What if we want to be an adaptable functor?
Will be summed up after reading the 8th chapter.
1.2 Functor (function call operator)