[英]Do I have to use std::forward when passing arguments pack to another variadic template function
How do I implement a function (foo) which passes a parameter pack to a function (bar) which finally passes that paramer pack to a class constructor? 如何实现将参数包传递给函数(栏)的函数(foo),该函数最终将参数包传递给类构造函数? This is the code:
这是代码:
template <typename... Args>
void bar(Args&&... args)
{
MyObj obj(std::forward<Args>(args)...);
/* Do something with obj */
}
Do I have to implement foo as 我是否必须将foo实现为
template <typename... Args>
void foo(Args&&... args)
{ bar(args...); }
Or 要么
template <typename... Args>
void foo(Args&&... args)
{ bar(std::forward<Args>(args)...); }
You need to use forward
. 您需要使用
forward
。 forward
looks like this: forward
看起来像这样:
template <class T>
constexpr T&& forward(typename std::remove_reference<T>::type& t) noexcept
{
return static_cast<T&&>(t);
}
(There is another overload of forward
, but it is irrelevant here.) (
forward
另一个重载,但在这里是无关紧要的。)
For each element Arg
of the template parameter pack Args
, Arg
can be either: ( T
is a non-reference type) 对于模板参数包
Args
每个元素Arg
, Arg
可以是:( T
是非引用类型)
T&
if the argument is a non-const lvalue, so that the parameter is of type T&
; T&
如果参数是非常量左值,则参数为T&
类型; or 要么
const T&
if the argument is a const lvalue, so that the parameter is of type const T&
; const T&
如果参数是const左值),则参数为const T&
类型; or 要么
T
if the argument is an rvalue, so that the parameter is of type T&&
. T
如果参数是一个rvalue,使得参数的类型的T&&
。
In the first case, forward<Arg>(arg)
instantiates to: 在第一种情况下,
forward<Arg>(arg)
实例化为:
constexpr T& forward(T& t) noexcept
{
return static_cast<T&>(t);
}
resulting in a non-const lvalue to be passed. 导致传递非常量左值。
In the second case, forward<Arg>(arg)
instantiates to: 在第二种情况下,
forward<Arg>(arg)
实例化为:
constexpr const T& forward(const T& t) noexcept
{
return static_cast<const T&>(t);
}
resulting in a const lvalue to be passed. 导致要传递一个常量左值。
In the last case, forward<Arg>(arg)
instantiates to: 在最后一种情况下,
forward<Arg>(arg)
实例化为:
constexpr T&& forward(T&& t) noexcept
{
return static_cast<T&&>(t);
}
resulting in an rvalue to be passed. 导致传递右值。
In all three cases, the value category is preserved, and the value is forwarded with modification to bar
. 在所有这三种情况下,值类别都会保留,并且值会修改为
bar
而转发。
If you don't use forward
, you will be unconditionally passing an lvalue, which is not desired. 如果不使用
forward
,则将无条件传递一个左值,这是不希望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.