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

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

我很感激关于如何重载派生类 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/

相关文章:

c++ - 在if语句中需要帮助

c++ - 隐式模板方法实例化

c++ - 重载 += 运算符作为友元函数

c++ - 如何打印二维对 vector 的值?

c++ - 所有数的最大公约数之和,直到 n 与 n

c++ - 带有 volatile 的 push_back 与 emplace_back

c++ - 在模板化类中返回模板变量的方法?

c++ - 定义类模板的友元函数模板

c++ - 指针和左移运算符的引用

c++,通过删除[] x [i]缩小动态数组