3.3 Function objects

In C, there are times that we need to pass pointers to functions as parameters. This allows important functions, such as comparison functions, to be specified at run-time. As a result, a subroutine can capture the abstract logic of an algorithm, but without binding to any particular methods of comparing.

In C++, we can define the invocation operator (operator()) for a class so that objects created from the class can be treated as functions.

The STL defines class templates for abstract functions such as less, plus, and etc. This makes it possible to specify operations as a parameters. For example, less<string>() creates an object that represents the “less than” comparison operator for strings. This object can, then, be passed to any subroutine or method that needs to know which way objects should be compared.

This construct is useful for many algorithms, such as is_sorted. Instead of fixing is_sorted to confirm increasing, decreasing, non-decreasing or non-increasing order, we can specify the expected sorting order as a parameter supplied to the algorithm.