为什么完美转发(包罗万象)无法实现复制分配?
Why doesn't perfect forwarding (catch-all) work to implement a copy-assignment?
在具有一系列 ctors(其中大部分只有一个参数)的 class 中,我希望所有单参数 ctors 也被相应的赋值运算符镜像。 ctor包括但不限于copy-ctor和move-ctor。所以这个,应该满足五法则。
template <typename T>
object& operator=(T&& from) {
// ...
return *this;
}
这是一个最小的例子:https://ideone.com/OKprcr(感谢@Daniel H 指出常量)。
我得到的错误是
error: object of type 'object' cannot be assigned because its copy assignment operator is implicitly deleted
...
note: copy assignment operator is implicitly deleted because 'object' has a user-declared move constructor
为什么函数模板没有实现复制赋值运算符?
Why doesn't the function template implement the copy-assignment operator?
因为标准是这么说的 ([class.copy.assign]/1):
A user-declared copy assignment operator X::operator=
is a non-static non-template member function of
class X
with exactly one parameter of type X
, X&
, const X&
, volatile X&
or const volatile X&
.
注意里面也没有 X&&
。
在具有一系列 ctors(其中大部分只有一个参数)的 class 中,我希望所有单参数 ctors 也被相应的赋值运算符镜像。 ctor包括但不限于copy-ctor和move-ctor。所以这个,应该满足五法则。
template <typename T>
object& operator=(T&& from) {
// ...
return *this;
}
这是一个最小的例子:https://ideone.com/OKprcr(感谢@Daniel H 指出常量)。
我得到的错误是
error: object of type 'object' cannot be assigned because its copy assignment operator is implicitly deleted
...
note: copy assignment operator is implicitly deleted because 'object' has a user-declared move constructor
为什么函数模板没有实现复制赋值运算符?
Why doesn't the function template implement the copy-assignment operator?
因为标准是这么说的 ([class.copy.assign]/1):
A user-declared copy assignment operator
X::operator=
is a non-static non-template member function of classX
with exactly one parameter of typeX
,X&
,const X&
,volatile X&
orconst volatile X&
.
注意里面也没有 X&&
。