Jump to content

Function object

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Wlievens (talk | contribs) at 13:06, 9 June 2004 (link to operator overloading). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In functional programming languages such as ML, a function object or functor represents a mapping that maps modules to modules, representing a tool for the reuse of code, and is used in a manner analogous to the original mathematical meaning of the term.

Recently, in C++ and Java, the term functor was coined, probably independently, with a meaning largely unrelated to category theory. In object-oriented software design a class can contain both data and function. The term functor was chosen to describe objects that represent the application of a function to (dynamic) parameter data.

This sort of functor has some of the characteristics that a function pointer would have in procedural languages such as C. In a procedural program, a sort function might accept a pointer to a "plain" function defining the ordering relation between items to be sorted. In a more object-oriented style, a sort method would accept a functor object that exposes a method defining the ordering.

In Java, the sort method signature would define the functor parameter in terms of a base class (typically an interface). In C++ the sort method would expect the functor class to define an appropriate application operator(). C++ also allows the possibility that the functor class itself is specified through a template argument.

Functors are more powerful than function pointers in that they may contain state (data) that can be used by the function represented. Compilers are sometimes able to generated improved code through inlining.

A functor often contains a single public method apart from the constructor, although this is not a strict limitation.

The C++ Standard Template Library makes a lot of use of functors, combining the functional programming paradigm with object oriented programming.