Function Object - in C and C++

In C and C++

Consider the example of a sorting routine that uses a callback function to define an ordering relation between a pair of items. A C program using function pointers may appear as:

#include /* Callback function */ int compareInts(void* a, void* b) { return *((int *)(a)) < *((int *)(b)); } ... /* Declaration of C sorting function */ void sort(void* firstItem, size_t itemSize, void* lastItem, int (*cmpfunc)(void *, void *)); ... int main(void) { int items = {4, 3, 1, 2}; sort((void *)(items), sizeof(int), (void *)(items + 3), compareInts); return 0; }

In C++ a function object may be used instead of an ordinary function by defining a class that overloads the function call operator by defining an operator member function. In C++ this is called a class type functor, and may appear as follows:

struct compareClass { bool operator(int a, int b) const { return a < b; } }; ... // Declaration of C++ sorting function. template void sortInts(int* beginItems, int numItems, ComparisonFunctor c); ... int main { int items = {4, 3, 1, 2}; sortInts(items, sizeof(items)/sizeof(items), compareClass); }

Notice that the syntax for providing the callback to the sortInts function is identical, but an object is passed instead of a function pointer. When invoked, the callback function is executed just as any other member function, and therefore has full access to the other members (data or functions) of the object.

It is possible to use function objects in situations other than as callback functions (although the shortened term functor is normally not used). Continuing the example,

compareClass Y; bool result = Y(a, b);

In addition to class type functors, other kinds of function objects are also possible in C++. They can take advantage of C++'s member-pointer or template facilities. The expressiveness of templates allows some functional programming techniques to be used, such as defining function objects in terms of other function objects (like function composition). Much of the C++ Standard Template Library (STL) makes heavy use of template-based function objects.

C++11 allows one to define anonymous function objects. The line from the prior example could be written as follows:

sortInts(items, sizeof(items)/sizeof(items), (int a, int b) { return a < b; });

Read more about this topic:  Function Object