Written on December 25, 2023
Functors are objects that can be used as though they are a function or function pointer.
In C++, a functor is an object that can be used like a function. This is achieved by providing an overload of the operator()
in a class. When you create an instance of such a class, you can use this instance as if it were a function by invoking it with the same syntax as a function call. This makes functors very flexible, as they can store state and have properties like regular objects, while still being usable as functions.
Here's a simple example of a functor in C++:
#include <iostream>
using namespace std;
class Adder {
public:
Adder(int n) : n_(n) {}
int operator()(int x) const {
return x + n_;
}
private:
int n_;
};
int main() {
Adder addFive(5);
cout << "Result: " << addFive(3) << endl; // Result: 8
return 0;
}
In this example, Adder
is a functor. It is initialized with a number, and when it is called as a function, it adds this number to its argument. The operator()
method makes this possible. This pattern is particularly useful in C++ for things like custom comparison functions in sorting algorithms, or for creating small function objects that carry state.
The key difference between using a functor and simply passing an additional variable to a function in C++ lies in the encapsulation of both state and behavior, as well as the potential for increased flexibility and efficiency.
Encapsulation of State and Behavior:
Adder
example, the state is the value to add (n_
), and the behavior is the addition operation itself.Object-Oriented Approach:
Flexibility and Reusability:
Efficiency in Certain Contexts:
Compatibility with STL and Other Libraries:
In summary, functors offer a more encapsulated, flexible, and potentially efficient way to bundle data and operations together, aligning with object-oriented principles and offering advantages particularly in templated and library code. Passing additional variables to functions is a simpler approach but lacks these advantages.