【问题标题】:Overloading the comparison operator== of derived class to scale for any number of base classes重载派生类的比较运算符 == 以针对任意数量的基类进行缩放
【发布时间】:2014-07-17 19:02:44
【问题描述】:

我很感激有关如何重载派生类Derived 的比较运算符operator== 的指针,以便它可以扩展到任意数量的基类Base1 , Base2 , Base3 , ...,(参见下面的代码, ideone 上的完整版)。我怀疑可以利用 bost MPL for_each 或一些类似的构造来调用基类(类型)的 list 上的比较。

// 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(抱歉遗漏)。

【问题讨论】:

  • 不是答案,但Base1::operator== (rhs)Base2::operator== (rhs) 不是更简单吗?

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


【解决方案1】:

你可以使用类似的东西:

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++11。我已经修改了我的问题。
  • @Olumide:实际上在 C++11 之前,您可以使用类型列表来实现这一点,但更麻烦
  • @DieterLücking 您的意思是类型列表?是的,我知道它们,但我很难在 Boost MPL 中找到任何类似于 Loki 风格的 TypeList。
  • @Olumide Here 是这个答案的非 c++11 版本,它使用 Boost.Preprocessor 来模拟可变参数模板。 (我还更改了函数的结构)。如果您想要超过 10 个碱基,则必须同时更改 BOOST_PP_REPEAT_FROM_TO 调用。
  • 你的回答提供了 C++03 实现思想的核心,所以我将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2017-04-12
相关资源
最近更新 更多