拉丁的传说
首先,让我们看一下std::forward根据标准执行的操作:§20.2.3 [forward] p2返回值: static_cast<T&&>(t)(这T是显式指定的模板参数,t它是传递的参数。)现在,请记住参考折叠规则:TR RT& & -> T& // lvalue reference to cv TR -> lvalue reference to TT& && -> T& // rvalue reference to cv TR -> TR (lvalue reference to T)T&& & -> T& // lvalue reference to cv TR -> lvalue reference to TT&& && -> T&& // rvalue reference to cv TR -> TR (rvalue reference to T)(从这个答案中偷偷偷走了。)然后,让我们看一下一个想要使用完美转发的类:template<class T>struct some_struct{ T _v; template<class U> some_struct(U&& v) : _v(static_cast<U&&>(v)) {} // perfect forwarding here // std::forward is just syntactic sugar for this};现在是一个示例调用:int main(){ some_struct<int> s1(5); // in ctor: '5' is rvalue (int&&), so 'U' is deduced as 'int', giving 'int&&' // ctor after deduction: 'some_struct(int&& v)' ('U' == 'int') // with rvalue reference 'v' bound to rvalue '5' // now we 'static_cast' 'v' to 'U&&', giving 'static_cast<int&&>(v)' // this just turns 'v' back into an rvalue // (named rvalue references, 'v' in this case, are lvalues) // huzzah, we forwarded an rvalue to the constructor of '_v'! // attention, real magic happens here int i = 5; some_struct<int> s2(i); // in ctor: 'i' is an lvalue ('int&'), so 'U' is deduced as 'int&', giving 'int& &&' // applying the reference collapsing rules yields 'int&' (& + && -> &) // ctor after deduction and collapsing: 'some_struct(int& v)' ('U' == 'int&') // with lvalue reference 'v' bound to lvalue 'i' // now we 'static_cast' 'v' to 'U&&', giving 'static_cast<int& &&>(v)' // after collapsing rules: 'static_cast<int&>(v)' // this is a no-op, 'v' is already 'int&' // huzzah, we forwarded an lvalue to the constructor of '_v'!}我希望这个循序渐进的答案可以帮助您和其他人了解其std::forward工作原理。