C++ Logo


Advanced search

Re: Curried <functional> function objects

From: Justin Bassett <jbassett271_at_[hidden]>
Date: Tue, 14 Apr 2020 18:38:15 -0700
Yes, I can do that. However, I can also do:

    std::transform(b1, e1, b2, e2, o, [](auto a, auto b) { return a + b; });

Yet we do have std::plus. std::plus makes it more readable. Those lambda
definitions work, but copy-pasting them everywhere is not productive. They
get pulled out into their own header file of function objects, so I just

    std::transform(b, e, dest, plus(1));

And now we're back where we started.

Another benefit, albeit small, is that implementations could match on these
function objects to provide more optimal implementations. For example:

    std::find_if(b, e, equal_to(2));
    // equivalent to:
    std::find(b, e, 2);
    // Possibly optimizable further into memchr

Can I just use these little personal library function objects? Yes.
However, perhaps it makes sense to have something like this in the standard
function objects. If it doesn't, no problem, I'll keep using them myself.


On Tue, Apr 14, 2020 at 6:11 PM Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>

> On Tue, Apr 14, 2020 at 8:41 PM Justin Bassett via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>> I use the function objects in <functional> all the time in conjunction
>> with algorithms. However, sometimes, I find that I really want a curried
>> function. For example:
>> find_if(b, e, not_equal_to(0));
>> transform(b, e, plus(1));
>> copy_if(b, e, o, less(0))
> In C++14, you can say
> auto plus1 = [](auto x) { return x + 1; };
> std::transform(b, e, dest, plus1);
> or even
> auto plus = [](auto x) { return [x](auto y) { return x + y; }; };
> std::transform(b, e, dest, plus(1));
> if the parameter absolutely *must* be substituted in at run time.
> Do these not fit your needs for production code? If not, why not?
> –Arthur

Received on 2020-04-14 20:41:27