As the name implies, it is an object that represents a function in a certain way. Typically, it refers to an instance of a class, which defines the application Operator ().
Function objects are more common than functions, because function objects can define persistent parts that span multiple calls (similar to static local variables ), at the same time, it can be initialized and checked outside the object (different from static local variables ). For example:
Class sum {
Int val;
Public:
Sum (int I): Val (I ){}
Operator int () const {return val;} // get the value
Int operator () (int I) {return Val + = I;} // Application
};
Void F (vector V)
{
Sum S = 0; // Initial Value 0
S = for_each (V. Begin (), V. End (), S); // calculate the sum of all elements
Cout <"the sum is" <S <"/N ";
// Or even:
Cout <"the sum is" <for_each (V. Begin (), V. End (), sum (0) <"/N ";
}
Note that a function object with an application operator can be perfectly inline because it does not involve any pointers, and the latter may cause a rejection of optimization. In contrast, the existing optimizer is almost impossible (or completely unavailable ?) Concatenates a call using a function pointer.
In the standard library, function objects are widely used for elasticity.