C++ - Function Objects (Functors)
In C++, a function object (or functor) is an object which implements the “operator()”. Thanks to this overload, the object call with parenthesis can be launched. With this behavior, your object looks like a function!
During this post, you will see some advantages to use functors. They are more flexible than function thanks to multiple advantages: Encapsulation, virtual functions, and arguments passing!
A simple example of functor in C++
A functor can be created by overloading the operator():
As you see here, my object is directly callable with the “objectName()” operator. It looks like a function but it is the call to the operator(). Thanks to this behavior, my multiplication looks like a function call.
The usage of functors in C++ algorithms.
Functors have a great advantage over functions: Their interactions with algorithms. In the next example, I show you how to set a simple “coefficient factor” in my multiply class. Then, this factor will be applied to an entire array smoothly!
In this example, I construct my object with a variable equal to 2. It is my coefficient factor. Combined with the function object “myMultiplicator”, I can multiply all elements in my list by my CF!
This is a simple example of functors usage. We could go further by using virtual methods. Or even templates!
Functors VS Lambda expressions.
You are certainly thinking that functors are like lambda expressions.
In fact, a lambda expression is a “nameless functor”. The only difference is about the complexity of your code: A lambda expression is simpler! Indeed, functors are taking few additional hidden data in C++.
This similitude is explained by the goal of a lambda expression: Lambdas are designed to create a “function object” capable of capturing variables in scope.
Another great advantage: You do not need C++11 specification to use functors. Indeed, functors are a great alternative to lambda expression if your job does not permit the usage of C++11. It is the case in multiple big company with huge code base.
Don't hesitate to exploit functors. It is a good alternative to lambda for multiple complex situations.