c – 通过通用引用传递的函数的std :: forward吗?

前端之家收集整理的这篇文章主要介绍了c – 通过通用引用传递的函数的std :: forward吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑以下两点:
template <class Function>
void apply(Function&& function)
{
    std::forward<Function>(function)();
}

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

在什么情况下有差异,它有什么具体的区别?

解决方法

如果Function的operator()具有ref限定符,则会有所不同.使用std :: forward,参数的值类别将被传播,如果没有它,则值类别将丢失,并且函数将始终作为l值调用. 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"
}
原文链接:https://www.f2er.com/c/115719.html

猜你在找的C&C++相关文章