functors
SummaryA Function Object, or Functor (the two terms are synonymous) is simply any object that can be called as if it is a function. An ordinary function is a function object, and so is a function pointer; more generally, so is an object of a class that definesoperator(). DescriptionThe basic function object concepts are Generator, UnaryFunction, and BinaryFunction : these describe, respectively, objects that can be called asf(), f(x), and f(x,y). (This list could obviously be extended to ternary function and beyond, but, in practice, no STL algorithms require function objects of more than two arguments.) All other function object concepts defined by the STL are refinements of these three.
Function objects that return
There is an important distinction, but a somewhat subtle one, between function objects and adaptable function objects. [1] In general, a function object has restrictions on the type of its argument. The type restrictions need not be simple, though :
Adaptable function objects are important because they can be used by function object adaptors : function objects that transform or manipulate other function objects. The STL provides many different function object adaptors, including
Finally, the STL includes many different predefined function objects, including arithmetic operations ( ExamplesFill aVector with random numbers. In this example, the function object is simply a function pointer. Vector<int> V(100);
generate(V.begin(), V.end(), rand);
Sort a struct less_mag : public binary_function<double, double, bool> { bool operator()(double x, double y) { return fabs(x) < fabs(y); } }; Vector<double> V; ... sort(V.begin(), V.end(), less_mag());
Find the sum of elements in a struct adder : public unary_function<double, void> { adder() : sum(0) {} double sum; void operator()(double x) { sum += x; } }; Vector<double> V; ... adder result = for_each(V.begin(), V.end(), adder()); <A href="#3">[3]</A> cout << "The sum is " << result.sum << endl;
Remove all elements from a List<int> L;
...
List<int> ::iterator new_end =
remove_if(L.begin(), L.end(),
compose2(logical_and<bool>(),
bind2nd(greater<int>(), 100),
bind2nd(less<int>(), 1000)));
L.erase(new_end, L.end());
Concepts
Types
FunctionsNotes[1] The reason for the name "adaptable function object" is that adaptable function objects may be used by function object adaptors.
[2] The
[3] This is an example of how to use function objects; it is not the recommended way of calculating the sum of elements in a vector. The See also | |||||||

