What the Functor?

   22 March 2007, early morning

A function object is any object that can behave like a function. A function object is commonly referred to as a functor, because function object takes too long to both say and type. In C++, we implement functors by creating classes that override operator(); syntactically, this makes a function call and a call to the member function operator() of the functor identical. Functors are used throughout the STL.

There are countless places where the STL requires you provide it with some code so that the generic task it aims to solve can be tailored to solve your specific task. Consider the STL set. When you instantiate a set you must provide the STL with information on how to sort the elements within it. (This class is implemented as a balanced-binary tree, and as such, needs to know how to keep the elements within it sorted.) You tell the STL how to sort your elements by supplying a function object that when given two elements from your class returns true when the first is “less than” the second — you define what it means for one object to the less than another.

This sort of behaviour would be implemented in C using call-back functions: supplying pointers to the functions you want some block of code to use. You can think of functors as the evolution of call-back functions; being proper classes, functors can encapsulate functionality nicely. Since functors do everything call-back functions do and more you should probably use them over call-back functions, more often not.



  1. Yes, one of the advantages of “being proper classes” is that functors can be stateful. :-)

    How do you think Java interfaces relate to call-back functions and functors? e.g. SortedSet works on objects that implement Comparable (or it’s given a functor).

Don't be shy, you can comment too!

Some things to keep in mind: You can style comments using Textile. In particular, *text* will get turned into text and _text_ will get turned into text. You can post a link using the command "linktext":link, so something like "google":http://www.google.com will get turned in to google. I may erase off-topic comments, or edit poorly formatted comments; I do this very rarely.