在子字段

时间:2017-02-27 08:21:21

标签: c++ c++11

我正在尝试std::movestd::forward的不同之处,我发现我无法在类字段上使用std :: forward:

name = std::forward<T>(rhs.name);

下面是完整的例子。我在gcc 6.3下得到的错误是:

C:/PROGRA~1/MINGW-~1/X86_64~3.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/6.3.0/include/c++/bits/move.h:89:7: error: static assertion failed: template argument substituting _Tp is an lvalue reference type
       static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"
       ^~~~~~~~~~~~~

我理解原因可能是因为T属于WrongUseOfMove类型。但我想知道是否只能转发子变量。例如,我可以使用rhs参数传递并将其字段转发给不同的类变量。

#include <iostream>
#include <string>
#include <vector>

class WrongUseOfMove {
 public:
  template<typename T>
  WrongUseOfMove(T&& rhs)
  {
    //name = std::move(rhs.name); // Very wrong!!
    //name = std::forward<T>(rhs.name); // Does not compile, T is WrongUseOfMove instead decltype(rhs.name);
    name = std::forward<decltype(rhs.name)>(rhs.name); // compiles - but is it correct? 
    std::cout << __PRETTY_FUNCTION__ << "\n";
  }

  WrongUseOfMove(){}

  std::string name;
};

int main()
{
  WrongUseOfMove wm;
  WrongUseOfMove wm2 = wm;
}

http://coliru.stacked-crooked.com/a/88d8591ee1478a3f

1 个答案:

答案 0 :(得分:3)

您可以使用直观的方式:

name = std::forward<T>(rhs).name;

Demo

你的尝试:

name = std::forward<decltype(rhs.name)>(rhs.name);

无条件移动:

Demo