I'm trying to create a fairly generic component system, where an object iterates over a bunch of other objects that all implement a certain interface. And this all works fine, however, I would also like to be able to get objects of a specific type (a la instanceOf), and I can't figure out how to do it.

Could anyone help me out?

[code]
interface I
{
        void update();
        void write();
}

class A : I
{
        int n;
        
        void update()
        {
                n++;
        }

        void write()
        {
                writeln(n);
        }
}

class B : I
{
        int m;
        
        void update()
        {
                m--;
        }

        void write()
        {
                writeln(m);
        }
}

class C
{
        I[] array;

        void addElem(I elem)
        {
                array ~= elem;
        }

        void loop()
        {
                foreach(elem; array)
                        elem.update();
        }

        void writeAll()
        {
                foreach(elem; array)
                        elem.write();
        }

        void writeB()
        {
                // Only call .write on B's
                // How do I get the B's from the array of I's?
        }
}

void main()
{
        C c = new C();

        c.addElem(new A());
        c.addElem(new B());

        c.loop();

        c.writeAll();

        c.writeB(); // This is the problem
}
[/code]

Reply via email to