+ 1

What is Functor's advantages

Hi.. I have reard people making statement that Functor maintains state... What does this mean? Below is my sample code: https://code.sololearn.com/cM5f19VvJ630/?ref=app What is advantage of Functor or need of the same? What I am trying to achieve is also doable by member function also... Please enlighten me... Thanks a lot.....

20th Jun 2020, 3:55 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Réponses
+ 4
And for a "real life" example, the STL itself uses functors a bunch. Maybe you've seen the C++ random number generators before: std::random_device rd; std::mt19937 engine(rd()); std::uniform_int_distribution<> dice(1, 6); int my_dice_roll = dice(engine); That snippet right there used functors twice: `rd` and `dice`. It's much eaiser on the eyes than say `dice.generate(engine)`.
20th Jun 2020, 4:23 PM
Schindlabua
Schindlabua - avatar
+ 4
Not that I'm aware of no. Looking at ChaoticDawg's SO link, back before C++ had lambdas, functors were the only way to get stateful functions. Now of course you can "functorize" everything by wrapping it in a lambda—the performance impact is negligible. (I do wanna add that what the C++ community calls functor and what the rest of the world calls functor are two different things. In case you are looking stuff up.)
21st Jun 2020, 7:22 AM
Schindlabua
Schindlabua - avatar
+ 2
Functors maintain state—as opposed to functions, which don't. Functions need all their data passed in as arguments, and functors, being objects, can store some data themselves. Consider this very sophisticated chess playing function: void play(int number, string move) { cout << "You played " << move << " on move #" << number; } versus a functor class Game { int number; public: operator()(string move) { cout << "You played " << move << " on move #" << number++; } } But that's just what OOP does for us, that's nothing new. There isn't really an advantage of overloading operator() over using member functions. However, some things are pretty function-like, finite state machines for example, so it makes sense to make them usable like functions. If it helps readability why not. in <algorithm> there are many functions that take functions as arguments and you can use functors instead so that's cool too: std::generate(vec.begin(), vec.end(), myfunctor);
20th Jun 2020, 4:17 PM
Schindlabua
Schindlabua - avatar
+ 1
Thanks Schindlabua and ChaoticDawg .... Does this means that member function also maintains state so does Functor. Correct that in case of normal function , we have to pass arguments... However, member functions are always there... So, does member function and Functor are same ? No added advantage of Functor over member function except look and feel of few developers ? No specific optimization in case of Functor ?
21st Jun 2020, 3:39 AM
Ketan Lalcheta
Ketan Lalcheta - avatar