开发者

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());
 开发者_如何学JAVA 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:

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.


This is impossible. For y1 and y4, then they both take rvalues of type A, but you want them to return different types. How should f know what to return?


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>.


auto y1 = f(A());
auto y4 = f(std::move(x));

Will not be distinguishable, as A() produce a temporary which will bind to A&&.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜