当我将函数参数用作std::forward的参数时,它们应该是std::forward_as_tuple参数吗?
template<class ... List>
void fn(List&& ... list){
// do I need this forward?
call_fn( forward_as_tuple( forward<List>(list)... ) );
}我知道它们将作为rvalue引用存储,但是还有什么需要考虑的吗?
发布于 2014-08-21 14:23:06
必须使用std::forward才能将参数的值类别保留为fn()。由于参数在fn中有一个名称,所以它们是lvalue,如果没有std::forward,它们总是以这样的方式传递给std::forward_as_tuple。
这种差异可以使用下面的例子来演示。
template<typename T>
void bar2(T&& t)
{
std::cout << __PRETTY_FUNCTION__ << ' '
<< std::is_rvalue_reference<decltype(t)>::value << '\n';
}
template<typename T>
void bar1(T&& t)
{
std::cout << __PRETTY_FUNCTION__ << ' '
<< std::is_rvalue_reference<decltype(t)>::value << '\n';
bar2(std::forward<T>(t));
bar2(t);
}bar1总是将它的参数传递给bar2,一次用std::forward,一次不使用。现在,让我们用lvalue和rvalue参数调用它们。
foo f;
bar1(f);
std::cout << "--------\n";
bar1(foo{});输出:
void bar1(T&&) [with T = foo&] 0
void bar2(T&&) [with T = foo&] 0
void bar2(T&&) [with T = foo&] 0
--------
void bar1(T&&) [with T = foo] 1
void bar2(T&&) [with T = foo] 1
void bar2(T&&) [with T = foo&] 0从输出中可以看到,在这两种情况下,如果不使用std::forward,则会将该参数作为lvalue传递给bar2。
发布于 2014-08-21 14:20:14
是的,您几乎肯定希望在这里使用std::forward,这是假设list中的参数在调用call_fn之后不使用。这是std::forward**,的一个典型用例,因为您希望使用完美转发**的语义。
它的参数的std::forward 保留值类别。 (即lvalue作为lvalue,rvalue为rvalue)。反过来,std::forward_as_tuple也会这样做,就像调用了std::tuple<List&&...>(std::forward<List>(list)...)一样。
关于“存储为rvalue引用”的说明。并不是参数包中的参数List都是rvalue引用(可能是),而是在这种情况下推导出的List,因此引用折叠将适用,推导出的类型可以是rvalue引用或lvalue引用。在创建std::tuple期间,您需要维护/保留这种区别。
发布于 2014-08-21 14:01:54
是的,如果你想保持完美的转发语义。在你的例子中:
template<class ... List>
void fn(List&& ... list)类型List&&,其中List实际上是一个模板参数,是一个通用参考而不是r值引用。因此,您应该将它们std::forward为std::forward_as_tuple函数,否则在std::forward_as_tuple中传递给fn的r值引用将由于引用折叠而可见为l值引用。
https://stackoverflow.com/questions/25427938
复制相似问题