在具有一系列 ctors(其中大部分只有一个参数)的类中,我希望所有单参数 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&&
。
关于c++ - 为什么完美转发(包罗万象)无法实现复制分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273390/