Search code examples
c++templatesoperator-overloadingboost-mpl

Overloading the comparison operator== of derived class to scale for any number of base classes


I'd appreciate pointers on how to overload the comparison operator operator== of a derived class, Derived, in such a way that it scales for any number of base classes, Base1 , Base2 , Base3 , ..., (see code below, full version on ideone). I suspect bost MPL for_each or some similar construct could probably be harnessed in order to invoke comparisons on a list of base class (types).

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

Edit

I cannot use C++11 (sorry for the omission).


Solution

  • You may use something like:

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

    And then

    bool Derived::operator==( const Derived& rhs ) const
    {
        return compare_bases<Derived, Base1, Base2>()(*this, rhs);
    }