Question

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 ?

Was it helpful?

Solution

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"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top