C++ Function Object

Introduction

Function object is any object for which the function call operator is defined, i.e., operator() is overloaded. It is also called functor.

Suppose we want to implement a function which requires a lot of parameters and the parameters would be set during runtime, using functors would be convenient because the parameters could be saved in the functor instance when it is created. This also means we can create a family of the functions using different parameters easily. In addition, by using C++ runtime polymorphism, i.e., function overriding, we could defer the functor type determination to runtime.

In this blog post, I would like to show some of the functor implementations.

Examples

The following example presents a couple of functors which use default and non-default parameters, how to pass functor to functions using pointer, and how to integrate functors with template.

To compile the program, please run the following command in the terminal.

Conclusions

Functors are less confusing and much easier to use compared to function pointers.

Lei Mao

02-10-2020

02-10-2020