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 ?

Vincent
  • 57,703
  • 61
  • 205
  • 388

1 Answers1

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"
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
  • Since when can one apply ref qualifiers to member function declarations? – Deduplicator Apr 25 '14 at 16:47
  • 2
    @Deduplicator: Since 2011. – Lightness Races in Orbit Apr 25 '14 at 16:49
  • @Deduplicator: Since `C++11`. The functionality is described in [n2439](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2439.htm). See [here](http://en.cppreference.com/w/cpp/language/member_functions) and [here](http://stackoverflow.com/q/8610571/485561). – Mankarse Apr 25 '14 at 16:50
  • 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. – Mark B Apr 25 '14 at 16:55
  • Thanks a lot for the background. If i see it right the single `&`-qualifier on the function is just for symmetry and emphasis. – Deduplicator Apr 25 '14 at 16:56