【发布时间】:2017-11-16 23:51:48
【问题描述】:
通常,当重载和赋值运算符时,应该检查自赋值。在一个简单的非模板类中,它需要以下内容:
MyClass& MyClass::operator=(const MyClass& rhs) {
if (this != &rhs) {
// do the assignment
}
return *this;
}
但是,假设 MyClass 是模板化的,并且我们想要泛化类可以具有的泛型类型的赋值运算符重载:
template<class T>
class MyClass
{
template<class U>
friend class MyClass;
T value;
template<class U>
MyClass<T>& operator=(const MyClass<U>& rhs)
//... other stuff
}
template<class T>
template<class U>
MyClass<T>& MyClass<T>::operator=(const MyClass<U>& rhs)
{
if (this != &rhs) { //this line gives an error
value = (T)rhs.value;
}
}
在上述情况下,if (this != &rhs) 行将给出编译器错误。在 MS Visual Studio 2015 中,是错误 C2446:
'==':没有从 'const MyClas *' 转换为 'MyClass *const '
因此,当使用可以在右侧获取通用模板类型的MyClass 实例的赋值运算符时,如何实现自赋值检查?
【问题讨论】:
标签: c++ c++11 templates operator-overloading assignment-operator