operator= 和 C++ 中未继承的函数?
在我刚刚进行的测试之前,我认为只有构造函数在 C++ 中没有被继承.但显然,赋值 operator=
不是太......
Until a test I've just made, I believed that only Constructors were not inherited in C++. But apparently, the assignment operator=
is not too...
- 这是什么原因?
- 是否有任何解决方法可以继承赋值运算符?
operator+=
,operator-=
, ... 也是这种情况吗?- 是否继承了所有其他函数(除了构造函数/operator=)?
- What is the reason of that ?
- Is there any workaround to inherit the assignment operator ?
- Is it also the case for
operator+=
,operator-=
, ... ? - Are all other functions (apart from constructors/operator=) inherited ?
事实上,我在做一些CRTP时遇到了这个问题:
In fact, I encountered this problem as I was doing some CRTP :
template<class Crtp> class Base
{
inline Crtp& operator=(const Base<Crtp>& rhs) {/*SOMETHING*/; return static_cast<Crtp&>(*this);}
};
class Derived1 : public Base<Derived1>
{
};
class Derived2 : public Base<Derived2>
{
};
有什么解决方案可以让它工作吗?
Is there any solution to get that working ?
好的,我已经隔离了问题.为什么以下不起作用?如何解决问题?
EDIT : OK, I have isolated the problem. Why the following isn't working ? How to solve the problem ?
#include <iostream>
#include <type_traits>
// Base class
template<template<typename, unsigned int> class CRTP, typename T, unsigned int N> class Base
{
// Cast to base
public:
inline Base<CRTP, T, N>& operator()()
{
return *this;
}
// Operator =
public:
template<typename T0, class = typename std::enable_if<std::is_convertible<T0, T>::value>::type>
inline CRTP<T, N>& operator=(const T0& rhs)
{
for (unsigned int i = 0; i < N; ++i) {
_data[i] = rhs;
}
return static_cast<CRTP<T, N>&>(*this);
}
// Data members
protected:
T _data[N];
};
// Derived class
template<typename T, unsigned int N> class Derived : public Base<Derived, T, N>
{
};
// Main
int main()
{
Derived<double, 3> x;
x() = 3; // <- This is OK
x = 3; // <- error: no match for 'operator=' in ' x=3 '
return 0;
}
推荐答案
赋值运算符在技术上是继承的;然而,它总是被派生类的显式或隐式定义的赋值运算符隐藏(参见下面的注释).
The assignment operator is technically inherited; however, it is always hidden by an explicitly or implicitly defined assignment operator for the derived class (see comments below).
(13.5.3 赋值) 赋值运算符应由只有一个参数的非静态成员函数.因为是副本赋值运算符 operator=
是为类隐式声明的,如果未由用户声明,基类赋值运算符始终是被派生类的复制赋值运算符隐藏.
(13.5.3 Assignment) An assignment operator shall be implemented by a non-static member function with exactly one parameter. Because a copy assignment operator
operator=
is implicitly declared for a a class if not declared by the user, a base class assignment operator is always hidden by the copy assignment operator of the derived class.
您可以实现一个虚拟赋值运算符,它只是将调用转发到基类 operator=
,如下所示:
You can implement a dummy assignment operator which simply forwards the call to the base class operator=
, like this:
// Derived class
template<typename T, unsigned int N> class Derived : public Base<Derived, T, N>
{
public:
template<typename T0, class = typename std::enable_if<std::is_convertible<T0, T>::value>::type>
inline Derived& operator=(const T0& rhs)
{
return Base<Derived, T, N>::operator=(rhs);
}
};
相关文章