Programming Techniques:Double Dispatch

From GPWiki
Jump to: navigation, search
40px-sprout.png   This article is a stub. You can help out by expanding it.


The following is an example of an implementation of double dispatch in C++.

    class A;
    class B;
 
    class Collidable
    {
    public:
        virtual void Collide( Collidable * x ) = 0;
        virtual void Collide( A * x ) = 0;
        virtual void Collide( B * x ) = 0;
    };
 
    class A : public Collidable
    {
    public:
        virtual void Collide( Collidable * x )
        {
            x->Collide( this );
        }
        virtual void Collide( A * a )
        {
            CollideAA( this, a ); // A-A
        }
        virtual void Collide( B * b )
        {
            CollideAB( this, b ); // A-B
        }
    };
 
    class B : public Collidable
    {
    public:
        virtual void Collide( Collidable * x )
        {
            x->Collide( this );
        }
        virtual void Collide( B * b )
        {
            CollideBB( this, b ); // B-B
        }
        virtual void Collide( A * a )
        {
            CollideAB( a, this ); // A-B
        }
    };
 
    void CollideAA( A * x, A * y )
    {
        // Do A-A collision
    }
 
    void CollideBB( B * x, B * y )
    {
        // Do B-B collision
    }
 
    void CollideAB( A * x, B * y )
    {
        // Do A-B collision
    }
 
    // Main collision function
    void Collide( Collidable * x, Collidable * y )
    {
        x->Collide( y );
    }