重载比较运算符==派生类以扩展任意数量的基类

时间:2014-07-17 19:02:44

标签: c++ templates operator-overloading boost-mpl

我很欣赏有关如何重载派生类operator==的比较运算符Derived的指针,以便它可以扩展任意数量的基类Base1 , Base2 , Base3 , ... ,(见下面的代码,ideone上的完整版)。我怀疑为了在基类(类型)的 list 上调用比较,可能会利用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(遗憾地抱歉)。

1 个答案:

答案 0 :(得分:7)

您可以使用以下内容:

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);
}