A functor is a powerful C++ entity that everyone who wants to master C++ needs to know. A functor, which is short for “function object”, is a C++ class that acts like a function. Functors can be called using the familiar function call syntax, and can yield values and accept parameters just like regular functions.
To create a functor, we create a class (or a struct) that overloads the function operator()
. Note here the function is called operator()
, and it’s not the operator
function, i.e. ()
. We then create an instance of this class (or struct) to use the created functor.
Create and use functors
Let’s look at two examples of creating and using a functor. In the first example, a functor is created with a class
, and in the second example we use a struct
to create the functor.