std::通过通用引用传递的函数的转发

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

本文关键字:函数 转发 引用 std      更新时间:2023-10-16

考虑以下两个:

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

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

在什么情况下会有区别,具体区别是什么?

如果Functionoperator()具有ref限定符,则会有所不同。有了std::forward,参数的值类别就会传播,没有它,值类别就会丢失,函数将始终作为l-value调用。活生生的例子。

#include <iostream>
struct Fun {
    void operator()() & {
        std::cout << "L-Valuen";
    }
    void operator()() && {
        std::cout << "R-Valuen";
    }
};
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-Valuen"
    apply_forward(Fun{}); // Prints "R-Valuen"
}