Possible to avoid RTTI?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mark A. Gibbs

    Possible to avoid RTTI?


    Given this situation:

    class Base
    {
    public:
    virtual ~Base();

    virtual bool equals(Base const&) const = 0;
    };

    Base::~Base() {}

    inline bool operator==(cons t Base& a, const Base& b)
    {
    return a.equals(b);
    }

    class Derived : public Base
    {
    public:
    bool equals(const Base& b) const
    {
    if (typeid(*this) == typeid(b))
    {
    return data_ == b.data_;
    }
    return false;
    }
    private:
    int data_;
    };

    // in use
    Base& a(getA());
    Base& b(getB());
    return a == b;

    Is there any way I can do this without RTTI?

    I was thinking of something like:

    class Base
    {
    public:
    virtual ~Base();

    virtual bool equals(Base const&) const = 0;

    protected:
    virtual void* type_() const = 0;
    };

    inline bool operator==(cons t Base& a, const Base& b)
    {
    return a.equals(b);
    }

    class Derived : public Base
    {
    public:
    bool equals(Base const&) const;

    protected:
    void* type_() const { return &i; }

    private:
    static int const i;
    };

    int const Derived::i = 0;

    But are there any other ways to do this?

    indi

  • Ruslan Abdikeev

    #2
    Re: Possible to avoid RTTI?

    "Mark A. Gibbs" <x_gibbsmark@ro gers.com_x> wrote in message
    news:MLadncJdDf 4b7sLcRVn-uw@rogers.com.. .[color=blue]
    > bool equals(const Base& b) const
    > {
    > if (typeid(*this) == typeid(b))
    > {
    > return data_ == b.data_;
    > }
    > return false;
    > }
    >
    > But are there any other ways to do this?[/color]

    This is a classic multimethod dispatch problem, which doesn't have clear
    solutions in C++.
    Introductory material may be found here

    There are other ways to implement this, e.g. see Alexandrescu.

    You may try to constraint the set of possible overrides to see if a simple
    double dispatch or something like that fits.

    Hope it helps,
    Ruslan Abdikeev.


    Comment

    • Ernst Murnleitner

      #3
      Re: Possible to avoid RTTI?

      Mark A. Gibbs wrote:
      [color=blue]
      >
      > Is there any way I can do this without RTTI?
      >[/color]

      Yes, there are certainly more ways. One is:

      make an enum like

      enum EClassTypes {baseClass, derivedClass};

      and implement

      EClassType Base::Type()
      {
      return baseClass;
      }

      EClassType Derived::Type()
      {
      return derivedClass;
      }

      In the comparison you have to replace
       if (typeid(*this) == typeid(b))
      by
      if (Type() == b.Type())


      Greetings
      Ernst


      --
      Ernst Murnleitner
      AWITE ist Ihr professioneller Partner bei Biogas | Biogasaufbereitung | Deponiegas | Power-To-Gas | Trockenfermentation | Gasanalyse | uvm

      Comment

      Working...