Benefits of Forwarding Links as Factor Arguments

There is so much talk about new C ++ forwarding links. However, sometimes in a specific situation it is still not clear to me whether they provide any advantage or not.

It is clear that passing heavy state functors (like random number generators) by value is not a good idea. So let me use the links. Okay, but...

... is there any advantage to using forwarding links such as

template <class T, class Functor>
T func(T x, Functor &&f)
{
    T y;
    // do some computations involving f(x) and store it in y
    return y;
}

instead of const links

template <class T, class Functor>
T func(T x, const Functor &f)
{
    T y;
    // do some computations involving f(x) and store it in y
    return y;
}

in functions that take object objects without sending them?

The main aspect of the issue is the assessment of effectiveness.

+4
source share
3 answers

, f, r, . , , , .

std::shuffle:

template< class RandomIt, class URNG >
void shuffle( RandomIt first, RandomIt last, URNG&& g );

URNG , 1) 2) ( - , RNG shuffle, RNG, , shuffle RNG "" ). const, operator() - RNG.

-const lvalue, URNG& URNG&&. rvalue URNG - , , - .

+6

Functor operator() const, const.

+3

, , const:

template <class T, class Functor>
T func(T x, Functor &&f)
{
    T y;
    y = f(x);
    return y;
}

template <class T, class Functor>
T func2(T x, const Functor &f)
{
    T y;
    y = f(x);
    return y;
}

int main()
{
    int a = 1;
    auto add_a = [=](int x) mutable { return ++a; };
    func(0, add_a); // compile
    func2(0, add_a); // does not compile
}

http://coliru.stacked-crooked.com/a/3eeb21a57d66452b

mutable lambda operator const (int)

, , . , .

+1

Source: https://habr.com/ru/post/1607560/


All Articles