Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::通过通用引用传递的函数的转发?_C++_C++11_Lambda_Perfect Forwarding_Universal Reference - Fatal编程技术网

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

C++ std::通过通用引用传递的函数的转发?,c++,c++11,lambda,perfect-forwarding,universal-reference,C++,C++11,Lambda,Perfect Forwarding,Universal Reference,考虑以下两个方面: template <class Function> void apply(Function&& function) { std::forward<Function>(function)(); } 模板 无效应用(函数和函数) { std::转发(函数)(); } 及 模板 无效应用(函数和函数) { 函数(); } 在什么情况下会有区别,具体区别是什么?如果函数的操作符()有ref限定符,则会有区别。使用std::forw

考虑以下两个方面:

template <class Function>
void apply(Function&& function)
{
    std::forward<Function>(function)();
}
模板
无效应用(函数和函数)
{
std::转发(函数)();
}

模板
无效应用(函数和函数)
{
函数();
}

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

如果
函数的
操作符()
有ref限定符,则会有区别。使用
std::forward
,参数的值类别将被传播,没有它,值类别将丢失,函数将始终作为l值调用

#包括
结构乐趣{
void运算符(){

std::cout从何时起可以将ref限定符应用于成员函数声明?@Deduplicator:Since 2011。@Deduplicator:Since
C++11
。中描述了该功能。请参阅和。您可能应该提到,这是因为该参数已命名,并且一旦它有名称,它将被视为L值,除非您
forward
它。非常感谢你的背景。如果我看得对的话,函数上的单个
&
-限定符只是为了对称和强调。搜索“perfect forwarding C++11”
template <class Function>
void apply(Function&& function)
{
    function();
}
#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"
}