【问题标题】:std::forward of a function passed via universal reference?通过通用引用传递的函数的 std::forward?
【发布时间】:2014-04-25 16:34:36
【问题描述】:

考虑以下两个:

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

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

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

【问题讨论】:

  • 搜索“完美转发C++11”

标签: c++ c++11 lambda perfect-forwarding universal-reference


【解决方案1】:

如果Functionoperator() 具有引用限定符,则存在差异。使用std::forward,参数的值类别被传播,没有它,值类别丢失,函数将始终作为左值调用。 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"
}

【讨论】:

  • 从什么时候开始可以将 ref 限定符应用于成员函数声明?
  • @Deduplicator:从 2011 年开始。
  • @Deduplicator:从C++11开始。该功能在n2439 中进行了描述。见herehere
  • 您可能应该提到这是因为参数已命名,并且一旦它有了名称,它将被视为L值,除非您forward它。
  • 非常感谢背景。如果我没看错的话,函数上的单个&amp;-qualifier 只是为了对称和强调。
猜你喜欢
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 2020-12-24
  • 2020-01-25
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
相关资源
最近更新 更多