问题描述
C ++ 0x显示使用std :: forward的示例:
C++0x shows an example of using std::forward:
template<class T>
void foo(T&& arg)
{
bar(std::forward<T>(arg));
}
使用std :: forward时总是有利吗?
When is it advantageous to use std::forward, always?
此外,它需要使用&&在参数声明中,它在所有情况下都有效吗?我想你必须传递临时函数,如果函数声明与&&在其中,所以可以用任何参数调用foo?
Also, it requires to use && in the parameters declaration, is it valid in all cases? I thought you had to pass temporaries to a function if the function was declared with && in it, so can foo be called with any parameter?
最后,如果我有一个函数调用,如:
Lastly, if I have a function call such as this:
template<int val, typename... Params>
void doSomething(Params... args) {
doSomethingElse<val, Params...>(args...);
}
我应该使用:
template<int val, typename... Params>
void doSomething(Params&&... args) {
doSomethingElse<val, Params...>(std::forward<Params>(args)...);
}
此外,如果在函数中使用两次参数,在同一时间,是明智的使用std :: forward?不会std :: forward转换相同的东西临时两次,移动内存,使其无效的第二次使用?将以下代码确定:
Also, if use the parameters twice in the function, i.e. forwarding to two functions at the same time, is it wise to use std::forward? Won't std::forward convert the same thing to a temporary twice, moving the memory and make it invalid for a second use? Would the following code be ok:
template<int val, typename... Params>
void doSomething(Params&&... args) {
doSomethingElse<val, Params...>(std::forward<Params>(args)...);
doSomethingWeird<val, Params...>(std::forward<Params>(args)...);
}
我对std :: forward感到困惑,
I'm a bit confused by std::forward, and I'd gladly use some clearing up.
推荐答案
使用它像第一个例子:
template <typename T> void f(T && x)
{
g(std::forward<T>(x));
}
template <typename ...Args> void f(Args && ...args)
{
g(std::forward<Args>(args)...);
}
这是因为:如果 T = U&
,则 T& = U&
,但如果 T = U&&&
,则 T& = U&&&
,所以你总是在函数体内得到正确的类型。最后,您需要 forward
将左值转换为 x
(因为它有一个名称!)回到
That's because of the reference collapsing rules: If T = U&
, then T&& = U&
, but if T = U&&
, then T&& = U&&
, so you always end up with the correct type inside the function body. Finally, you need forward
to turn the lvalue-turned x
(because it has a name now!) back into an rvalue reference if it was one initially.
但是,你不能转发一个以上的东西,因为这是没有意义的。转发意味着您可能会将该参数一直移动到最终调用者,一旦移动,它就会消失,因此您无法再使用。
You cannot forward something more than once, though, because that makes no sense. Forwarding means that you're potentially moving the argument all the way through to the final caller, and once it's moved it's gone, so you cannot then use it again.
这篇关于何时使用std :: forward转发参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!