std::forward of a function passed via universal reference?
Asked Answered
T

1

7

Consider the two following:

template <class Function>
void apply(Function&& function)
{
    std::forward<Function>(function)();
}

and

template <class Function>
void apply(Function&& function)
{
    function();
}

In what case is there a difference, and what concrete difference is it ?

Terenceterencio answered 25/4, 2014 at 16:34 Comment(1)
search for "perfect forwarding C++11"Alkaloid
B
12

There is a difference if Function's operator() has ref qualifiers. With std::forward, the value category of the argument is propagated, without it, the value category is lost, and the function will always be called as an l-value. Live Example.

#include <iostream>

struct Fun {
    void operator()() & {
        std::cout << "L-Value\n";
    }
    void operator()() && {
        std::cout << "R-Value\n";
    }
};

template <class Function>
void apply(Function&& function) {
    function();
}

template <class Function>
void apply_forward(Function&& function) {
    std::forward<Function>(function)();
}

int main () {
    apply(Fun{});         // Prints "L-Value\n"
    apply_forward(Fun{}); // Prints "R-Value\n"
}
Burglarious answered 25/4, 2014 at 16:42 Comment(5)
Since when can one apply ref qualifiers to member function declarations?Mariellamarielle
@Deduplicator: Since 2011.Offshore
@Deduplicator: Since C++11. The functionality is described in n2439. See here and here.Burglarious
You should probably mention that this is because the parameter is named, and as soon as it has a name it will be treated as an L-value unless you forward it.Wellmannered
Thanks a lot for the background. If i see it right the single &-qualifier on the function is just for symmetry and emphasis.Mariellamarielle

© 2022 - 2024 — McMap. All rights reserved.