当一个函数接受对另一个函数的转发引用时,使用 std::forward 调用该函数有何影响

gre*_*g_p 2 c++ perfect-forwarding

只是想知道转发函数模板参数的确切影响(和优点)是什么,即:

template <class F>
void foo(F &&f) {
   f(1);                    // how does this call
   std::forward<F>(f)(1);   // differ from this one?
}
Run Code Online (Sandbox Code Playgroud)

app*_*ple 5

仅当函数operator()被左值/右值重载时

struct X{
    void operator()(int)&;  // 1
    void operator()(int)&&; // 2
};

template <class F>
void foo(F &&f) {
   f(1);                    // always calls 1
   std::forward<F>(f)(1);   // calls 2 when F is rvalue
}
Run Code Online (Sandbox Code Playgroud)

一般移动语义适用,在f作为右值调用后,不应再次使用它。(除非你检查状态)