在子字段上使用std :: forward [英] Using std::forward on sub fields
问题描述
我正在尝试 std :: move
和 std :: forward
有何不同,我发现我无法在类字段上使用std :: forward:
I was experimenting with how std::move
and std::forward
differs, and I have found that I am not able to use std::forward on class field:
name = std::forward<T>(rhs.name);
是完整示例。我在gcc 6.3下遇到的错误是:
below is full example. The error I am getting under gcc 6.3 is:
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
参数并将其字段转发给不同的类变量。
I understand that the cause is probably because T
is of type WrongUseOfMove
. But I wonder if forwarding only a sub variable is possible. For example I could use passed in rhs
parameter and forward its fields to different class variables.
#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
推荐答案
您可以使用直观的方式:
You may use the intuitive way:
name = std::forward<T>(rhs).name;
您的尝试:
name = std::forward<decltype(rhs.name)>(rhs.name);
进行无条件移动:
< a href = http://coliru.stacked-crooked.com/a/7dfe6e0d9a66f2f6 rel = nofollow noreferrer>演示
这篇关于在子字段上使用std :: forward的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!