Possible to avoid RTTI?

M

Mark A. Gibbs

Given this situation:

class Base
{
public:
virtual ~Base();

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

Base::~Base() {}

inline bool operator==(const 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==(const 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
 
R

Ruslan Abdikeev

Mark A. Gibbs said:
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?

This is a classic multimethod dispatch problem, which doesn't have clear
solutions in C++.
Introductory material may be found here
http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html
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.
 
E

Ernst Murnleitner

Mark said:
Is there any way I can do this without RTTI?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top