|
![](/i/fill.gif) |
clipka <ano### [at] anonymous org> wrote:
> (You could achieve the same syntax by having multiplierFunction() return
> an object with an overridden () operator rather than a function, but of
> course that would be cheating.)
That's kind of what the C++ lambda does internally: It puts the captured
variables in some kind of internal struct, which the function then operates
with (similarly to how a class member function operates with the object
using the 'this' pointer). You could achieve a similar behavior by writing
a class, but a lambda achieves this with significantly less effort.
There is a significant difference to a class, though. In this example
std::function<int(int)> can manage *any* lambda function that takes an
int and returns an int, not just ones that have captured a 'multiplier'
variable and perform a "value * multiplier" on it.
If you implemented the functionality of the example I wrote with a
class, you would be fixing the "lambda" function to be only and exactly
a multiplier function that has to be used with exactly your class and
nothing else. std::function<int(int)> has no such limitation. Any function
(be it a static function or a lambda) that takes an int and returns one
will do.
This can make a difference especially with non-templated functions that
take a std::function as parameter. (One advantage of std::function over a
generic functor is that the former does not require for the code that uses
it to be templated and thus doesn't suffer form the few limitations that
templated code has.)
--
- Warp
Post a reply to this message
|
![](/i/fill.gif) |