[英]Perfect forwarding
If we have the following:如果我们有以下情况:
template <class T>
struct B{
T data;
}
struct A{
int data_array[100];
}
int main()
{
A x;
const A x_const;
auto y1 = f(A());
auto y2 = f(x);
auto y3 = f(x_const);
auto y4 = f(std::move(x));
}
I want to know an f
(preferably function, but macro is okay also) such that:我想知道一个
f
(最好是 function,但宏也可以)这样:
decltype(y1) == B<A>
decltype(y2) == B<A&>
decltype(y3) == B<const A&>
decltype(y4) == B<A&&>
That is, f
perfectly forwards x
into an object of B
.也就是说,
f
完美地将x
转发到B
的 object 中。
This is impossible.这是不可能的。 For
y1
and y4
, then they both take rvalues of type A, but you want them to return different types.对于
y1
和y4
,它们都采用 A 类型的右值,但您希望它们返回不同的类型。 How should f
know what to return? f
应该如何知道返回什么?
template <typename T>
auto f(T&& t) -> B<decltype(std::forward<T>(t))>
{
return B<decltype(std::forward<T>(t))>{std::forward<T>(t)};
}
This does almost what you want.这几乎可以满足您的需求。 The only difference is for the first one the type is
B<A&&>
rather than B<A>
.唯一的区别是第一个类型是
B<A&&>
而不是B<A>
。
auto y1 = f(A());
auto y4 = f(std::move(x));
Will not be distinguishable, as A()
produce a temporary which will bind to A&&
.将无法区分,因为
A()
会产生一个临时绑定到A&&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.