Perfect shipment

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 f(preferably a function, but the macro is fine too) to:

decltype(y1) == B<A>
decltype(y2) == B<A&>
decltype(y3) == B<const A&>
decltype(y4) == B<A&&>

That is, it fperfectly transfers xto the object B.

+5
source share
3 answers

It's impossible. For y1and y4, they both take values ​​of type A, but you want them to return different types. How fto know what to return?

+8
source
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 is almost what you want. The only difference is that for the first type, type B<A&&>, not B<A>.

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

, A() , A&&.

+2

All Articles