Simulate dynamic cast without RTTI

Viewed 193

On a simple embedded platform I have no RTTI available but I want to use c++ advantages like inheritance for a class hierarchy like the provided sample. At the moment I'm using the following code snipped to simulate a dynamic cast. To simplify this discussion I ported the code to a simple main.cpp. I used the mingw compiler for testing my sample. The code is working as expected but seams not ideal. I'm not searching for a generic dynamic cast replacement solution considering all aspects. Is there any way to implement this cast with less effort?

class I_BC
{
public:
    virtual ~I_BC() {}
    virtual int getI_BC() = 0;
};

class I_C
{
public:
    virtual ~I_C() {}
    virtual int getI_C() = 0;
};

class A
{
public:
    virtual ~A() {}
    int xx() {return 1;}

    template <typename T>
    T* cast() { return nullptr;}

protected:
    virtual I_BC* cast2BC() {return nullptr;}
    virtual I_C* cast2C() {return nullptr;}
};

template <>
I_BC* A::cast<I_BC>()  {return this->cast2BC();}
template <>
I_C* A::cast<I_C>()  {return this->cast2C();}

class B : public A, public I_BC
{
public:
    int getI_BC() override  { return 0xB000000C;}
    int bar() {return 2;}

protected:
    I_BC* cast2BC() override {return this;}
};

class C : public A, public I_BC, public I_C
{
public:
    int foo() {return 3;}
    int getI_C() override   { return 0xC000000C;}
    int getI_BC() override  { return 0xC00000BC;}

protected:
    I_BC* cast2BC() override {return this;}
    I_C* cast2C() override {return this;}
};


#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
    A* a = new B();

    // Ok I know that B implement I_BC interface so cast it now
    I_BC* bc = a->cast<I_BC>();
    cout << "Res : 0x" << hex << bc->getI_BC() << endl;

}
1 Answers
Related