Avatar ·

What are functors in C++ and what are they used for?

Hello colleagues! I started learning C++ and came across the term "functor". I read the documentation but didn't fully understand it. It seems to be a class object that behaves like a function. But why is this needed? We have regular functions, lambdas, and function pointers. I tried to write a simple example, but I'm not sure if this is the correct usage. Here's what I got: ```cpp #include class Adder { public: int operator()(int a, int b) { return a + b; } }; int main() { Adder add; std::cout << add(3, 4) << std::endl; // Outputs 7 return 0; } ``` I understand that this works, but how is it better than a regular function `int add(int a, int b)`? Why bother with an entire class? I've heard that functors are used in STL, for example, in algorithms. But I