c++ - 如何在没有 dynamic_cast 的派生类型上实现 "less"?

标签 c++ class inheritance operator-overloading virtual

我想在以下类上实现“less”类型的操作:

class Base {
  public:
    virtual int type() const = 0;
  private:
    int b;
};

class Derived1 : public Base{
  public:
    virtual int type() const { return 1; }
  private:
    int d1; 
};

class Derived2 : public Base{
  public:
    virtual int type() const { return 2; }
  private:
    int d2;
};

哪里o1 < o2如果其类型较小且类型相等,则比较元素(首先是 b,然后是 d1 或 d2)。

请注意,还有其他具有类似问题结构的操作(例如等于)。

如何在不使用 dynamic_cast 的情况下执行此操作? ?

最佳答案

您不需要dynamic_casttype。就此而言,也根本没有公共(public)成员。

class Base {
  virtual bool less( Base const & rhs ) const {
    return false;
  }

  int b;

  friend bool operator < ( Base const & lhs, Base const & rhs ) {
    std::type_info const & ltype = typeid (lhs);
    std::type_info const & rtype = typeid (rhs);
    if ( ltype == rtype ) {
      if ( lhs.b < rhs.b ) return true;
      if ( rhs.b < lhs.b ) return false;
      return lhs.less( rhs ); // Dynamic types of lhs and rhs already match.
    }
    return ltype.before( rtype );
  }
};

class Derived1 : public Base{
  virtual bool less( Base const & rhs_base ) const {
    // Since rhs_base is known to be of this type, use static_cast.
    Derived1 const & rhs = static_cast< Derived1 const & >( rhs_base );
    return d1 < rhs.d1;
  }

  int d1; 
};

// Same for Derived2

http://coliru.stacked-crooked.com/a/af1aae28630878f5 (包括测试)

关于c++ - 如何在没有 dynamic_cast 的派生类型上实现 "less"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024012/

相关文章:

Python:尝试将函数参数传递给类中的另一个函数,得到 NameError:未定义名称 ' '

c++ - 尝试更改二维 vector 的值时出现问题

c++ - 不同的函数有不同的地址吗?

javascript - 如何显示特定类的div

PHP - 扩展、库与类 - 何时以及为何

c# - 为什么 C# 数组没有 Count 属性?

c++ - 模板化(或以某种方式自动)方法的返回值

JavaScript 继承与工作代码助手和大纲?

c++ - 如何从延迟的 CustomAction (c++ dll) 设置 WiX 属性

c++ - 为什么 unique-ptr 不检查基类是否可虚拟破坏?