Got 3 sisters fighting in mind: (function object, function pointer, lambda function)


Hi Experts,

I got 3 sister concepts playing and colliding in my mind. I know each can be passed to another function. All of them seem to me like alternatives with subtle differences.

1. function pointer: a pointer to a function

2. function object: instance of a class that has overloaded the () operator; capable of acting as a function;

3. lambda function: an anonymous function (newly introduced in C++11) that may be defined on the spot and that exists only during the lifetime of the statement of which it is a part

Because of the subtilities, I wonder which of the 3 choices would be the most appropriate in a given scenario. So, experts out there, kindly shed some light (on some selection criteria?) so that I could decide and use them in different scenarios.

BR,
softwarelover
Your description of "3" is not entirely correct. A lambda expression is an expression that creates a function object, that is, "an instance of a class that has overloaded the () operator". You can save it in a std::function or in an auto variable - it doesn't have to die at the end of a statement.

Also, don't forget the many other ways you can create a function object: from the predefined std::plus or std::less or, say std::uniform_int_distribution, to the multipurpose std::bind, std::function and std::mem_fn. Even std::ref can produce a function object.

(speaking of which, you also forget reference to function as another something that can be passed to another function and invoked)
> I wonder which of the 3 choices would be the most appropriate in a given scenario.

A few of the issues involved were discussed here:
http://www.cplusplus.com/forum/general/63061/
You guys are brilliant. :)
Topic archived. No new replies allowed.