Function object
Classes that define call operators. Their objects are often called function objects, that is, they are objects that act similar functions.
Struct absint
{
Int operator () (INT Val)
{
Return Val <0? -Val: Val;
}
};
Int I =-42;
Abdint absobj;
Unsigned int UI = absobj (I); // callabout absint: Operator (INT)
The function call operator must be declared as a member function. We can still "call" this object to run the overload call operator defined by the absobj object, this operator accepts an int value and returns its absolute value. Function call operators must be defined as member functions and can be overloaded.
Function objects are used for standard library algorithms,
Bool gt6 (const string & S)
{
Return S. Size ()> = 6;
}
Vector <string >:: size_type WC = count_if (words. Begin (), words. End (), gt6 );
Use gt6 as the pass to count_if
Calculate the number of words that make gt6 return true.
Class gt_cls
{
Public:
Gt_cls (size_t val = 0): bound (Vala ){}
Bool operator () (const string & S)
{
Return S. Size ()> = bound;
}
PRIVATE:
STD: String: size_type Blund;
};
Count_if (words. Begin (), words. End (), gt_cls (6) // test the number of characters with a length greater than 6.
Function objects defined in the standard library
Arithmetic function object type
+-*/Plus <type>
Relational function object type
=! ==>=<<=
Logical function object type
& |!
All of the above have been defined as a template class, which can be used as a function object during instantiation.
In the original definition, the function object is an object with behavior similar to the function, and the object is an instance of the class ..