문제

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 ?

도움이 되었습니까?

해결책

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"
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top