完美转发

Cli*_*ton 5 c++ forwarding decltype c++11

如果我们有以下内容:

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));
}
Run Code Online (Sandbox Code Playgroud)

我想知道f(最好是功能,但宏也可以),这样:

decltype(y1) == B<A>
decltype(y2) == B<A&>
decltype(y3) == B<const A&>
decltype(y4) == B<A&&>
Run Code Online (Sandbox Code Playgroud)

也就是说,f完美地x转化为一个对象B.

Pup*_*ppy 8

这是不可能的.对于y1y4,然后它们都采用类型A的rvalues,但是你希望它们返回不同的类型.应该f怎么知道返回什么?

  • @ HighCommander4问题的区别在于一个是prvalue而另一个是xvalue.由于参数传递只允许区分左值和右值,因此确实不可能检测到函数内部的差异(这是设计的). (5认同)
  • @HighCommander4:他们都是左撇子.没有参考或其他语言结构可以区分A和未命名的A && - 事实上,它是你不能的一半. (2认同)

HC4*_*ica 3

template <typename T>
auto f(T&& t) -> B<decltype(std::forward<T>(t))>
{
    return B<decltype(std::forward<T>(t))>{std::forward<T>(t)};
}
Run Code Online (Sandbox Code Playgroud)

几乎可以满足您的要求。唯一的区别是第一个类型是类型B<A&&>而不是B<A>