All pastes #676179 Raw Edit

Untitled

public text v1 · immutable
#676179 ·published 2007-08-30 20:51 UTC
rendered paste body
class A
{
public:
    char m_type;
    A(char type = 0) : m_type(type) {}
};
class B : public A
{
public:
    B() : A(1) {}
};
class C : public A
{
public:
    C() : A(2) {}
};

class Base
{
public:
    virtual void F1(A *p) = 0;
};

class Child : public Base
{
public:
    void F1(A *p);

    void F1A(A *p)
    {
        printf("Child A\n");
    }
    void F1B(B *p)
    {
        printf("Child B\n");
    }
    void F1C(C *p)
    {
        printf("Child C\n");
    }
};

typedef (Child::*ChildMethod)(A *);

ChildMethod methods[] =
{
    (ChildMethod)&Child::F1A,
    (ChildMethod)&Child::F1B,
    (ChildMethod)&Child::F1C
};

#define USE_SWITCH

void Child::F1(A *p)
{
#ifndef USE_SWITCH
    (this->*methods[p->m_type])(p);
#else
    switch(p->m_type)
    {
        case 0: F1A(p); break;
        case 1: F1B((B*)p); break;
        case 2: F1C((C*)p); break;
    }
#endif
}

void main()
{
    Child x;
    A *a = new A;
    A *b = new B;
    A *c = new C;
    x.F1(a);
    x.F1(b);
    x.F1(c);
    getch();
}