O'Neil
O'Neil

Reputation: 3849

Utility of std::forward<Func> at call

I am coding functions like the well known tuple_apply, which take a rvalue reference of a Function as parameter. During my researches on the web, I came across the two following calls:

template <
    typename Func,
    /* stuff */
>
void myfunction(Func && func, /* stuff */)
{
    std::forward<Func>(func)(/* stuff */); // use of std::forward before call
    func(/* stuff */);                     // direct call
}

Is this call to std::forward really usefull ? If so why ?

Thanks for your enlightenment!

Upvotes: 1

Views: 79

Answers (1)

Mikhail
Mikhail

Reputation: 21749

In most scenarios there are no difference between these two options. However, Func may have ref-qualified operator(). Like the following:

struct Func {
    operator()(/* stuff */) &&;
}

This can be called only on r-values, so the second call will not compile, since func inside myfunction is an l-value. Or it can have ref-qualified overloads:

struct Func {
    operator()(/* stuff */) &;
    operator()(/* stuff */) &&;
}

In this case call without std::forward will use the first overload regardless of what is passed to myfunction: an l-value or an r-value. A call with std::forward, on the other side, will pick appropriate overload based on l-valueness of the passed func object.

Upvotes: 2

Related Questions