我很感激关于如何重载派生类 Derived
的比较运算符 operator==
的指示,以便它可以扩展到任意数量的基类,Base1 , Base2 , Base3 , ...
,(参见下面的代码,完整版在 ideone 上)。我怀疑可以利用 bost MPL for_each 或一些类似的构造来调用基类(类型)的列表 上的比较。
// Real problem has many more more Base classes
class Derived : public Base1 , public Base2
{
public:
Derived( unsigned& val1 , unsigned& val2 ) : Base1( val1 ) , Base2( val2 )
{
}
// Can the following sequence of steps be generalized
// for an arbitrary number of base classes?
bool operator==( const Derived& rhs ) const
{
const Base1& rhsBase1 = rhs;
const Base2& rhsBase2 = rhs;
const Base1& thisBase1 = *this;
const Base2& thisBase2 = *this;
return ( thisBase1 == rhsBase1 ) && ( thisBase2 == rhsBase2 );
}
};
编辑
我不能使用 C++11(抱歉遗漏了)。
最佳答案
你可以使用类似的东西:
template <typename T, typename Base, typename ...Bases>
struct compare_bases {
bool operator () (const T&lhs, const T& rhs) const {
return static_cast<const Base&>(lhs) == static_cast<const Base&>(rhs)
&& compare_bases <T, Bases...>()(lhs, rhs);
}
};
template <typename T, typename Base>
struct compare_bases<T, Base> {
bool operator()(const T&lhs, const T& rhs) const {
return static_cast<const Base&>(lhs) == static_cast<const Base&>(rhs);
}
};
然后
bool Derived::operator==( const Derived& rhs ) const
{
return compare_bases<Derived, Base1, Base2>()(*this, rhs);
}
关于c++ - 重载派生类的比较运算符==以扩展任意数量的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811497/