Why use `std::bind_front` over lambdas in C++20?

后端 未结 2 755
臣服心动
臣服心动 2021-02-06 21:10

As mentioned in a similarly worded question (Why use bind over lambdas in c++14?) The answer was - no reason (and also mentioned why it would be better to use lambdas).

M

2条回答
  •  别那么骄傲
    2021-02-06 21:29

    The paper that proposed it Simplified partial function application has some good compelling use cases. I will summarize them here, because otherwise I would have to quote most of the paper, so definitely go check it out:

    Automatic perfect forwarding

    Using a lambda would involve std::forward boilerplate

    Propagating mutability

    In case of storing object by value std::bind and std::bind_front propagate constness, but in the case of capturing lambda the user must chose a mutable or const version creating problems

    Preserving return type

    Using a lambda would involve -> decltype(auto) boilerplate on the user side.

    Preserving value category

    Like preserving mutability, except now we are talking about lvalue/rvalue and only std::bind_front does this correctly

    Supporting one-shot invocation

    A consequence of propagating mutability and preserving value category

    Preserving exception specification

    This is especially more important now since exception specification is now part of type system


    cppreference has some useful notes as well:

    This function is intended to replace std::bind. Unlike std::bind, it does not support arbitrary argument rearrangement and has no special treatment for nested bind-expressions or std::reference_wrappers. On the other hand, it pays attention to the value category of the call wrapper object and propagates exception specification of the underlying call operator.

提交回复
热议问题