0

I am a C++ developer. Recently, I came across the concept of function objects. But I was wondering about the usages of function objects in day to day coding. Please put some light on such usage which will make the code cleaner or more efficient.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
paper.plane
  • 1,201
  • 10
  • 17
  • Have a look at this : http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html – eracube Jun 16 '16 at 10:34
  • 2
    possible duplicate of http://stackoverflow.com/questions/356950/c-functors-and-their-uses – Gaurav Sehgal Jun 16 '16 at 10:35
  • 3
    If you look at [the algorithm functions in the standard library](http://en.cppreference.com/w/cpp/algorithm), many of them take a *predicate* as argument, and that predicate is something that is callable, like a function object instance. – Some programmer dude Jun 16 '16 at 10:36
  • @JoachimPileborg And function objects usually do not take any memory space, unlike function pointers. – Revolver_Ocelot Jun 16 '16 at 10:51
  • @Revolver_Ocelot Well it depends if the function objects needs to store data internally or not. Having a function object whose constructor takes an argument and stores some data internally to be used by the `operator()` function is not unusual. – Some programmer dude Jun 16 '16 at 11:05
  • 1
    @JoachimPileborg Yes you are right. I was talking about stateless functors and choice "free function or function object". For example, `unique_ptr` taking pointer to function as deleter is twice as large as `unique_ptr` taking function object wrapping same function, because pointers are not stateless. – Revolver_Ocelot Jun 16 '16 at 11:19

2 Answers2

0

Functors in the C++ meaning of the word is what makes the closure behaviour of lambdas introduced with C++ 2011 'possible'.

user268396
  • 11,576
  • 2
  • 31
  • 26
0

Functors are mostly used for handle events.

For example, an Event object will have functors attributes. When the event is triggered, functions pointed by the functors will be executed.

Another example : you have a Plot object allowing to draw curves. You can give a functors arguments, whick point to the function allowing to compute points of the curve.