Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::forward of a function passed via universal reference?

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 ?

like image 725
Vincent Avatar asked Apr 25 '14 16:04

Vincent


1 Answers

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"
}
like image 105
Mankarse Avatar answered Sep 20 '22 03:09

Mankarse