POV-Ray : Newsgroups : povray.off-topic : I'm in the mood for monads : Re: I'm in the mood for monads Server Time
29 Jul 2024 14:22:28 EDT (-0400)
  Re: I'm in the mood for monads  
From: Warp
Date: 22 Apr 2012 13:03:36
Message: <4f9439e8@news.povray.org>
clipka <ano### [at] anonymousorg> 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

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.