1, the concept of the function of imitation
Functor (functor) is the use of a class that looks like a function. Its implementation is to implement a operator () in a class, and this class has a function-like behavior, which is a pseudo-function class.
When writing code, it is sometimes found that some functions of the implementation of code, will continue to be used in different member functions, but it is not good to separate the code into a class of a member function. But I want to reuse the code.
(1) Write a common function, can, this is a solution, but some variables used by the function, it is possible to become a public global variable, and in order to reuse such a piece of code, it is necessary to single out a function, is not very good maintenance.
(2) It is possible to write a simple class with an imitation function, except for the member functions that maintain a class, just implement a operator (), and in the case of the class instantiation, the non-parametric elements that will be used are passed into the class. This eliminates the global maintenance of some of the public variables. You can also make the code stand out for the next reuse. And these functor can also be used in association, aggregation, dependency of the relationship between the classes, and the use of their classes together, so that the management of resources (this is probably the most significant advantages of its relative to the function). If in conjunction with the template technology and policy programming ideas, it is more powerful, we can slowly experience.
2. Example of an imitation function
classpoint{ Public: Point () {_x= _y =0; } Point&operator()(intDxintdy) {_x+ = DX; _y + = dy;return* This; }Private: int_x, _y;};intMain () {Point pt; PT (3,2 );}
Note that the invocation of an affine function uses the class name instead of the function name.
C + + profiling functions