How do I find the actual types of the elements in a list of classes?

Jack Stouffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 13 13:23:53 PDT 2015


Given:

--------------------
interface Parent {
         void method();
}

class A : Parent {
         void method() {}

         this() {}
}

class B : Parent {
         void method() {}
         void method2() {}

         this() {}
}

void main() {
         import std.stdio;

         Parent[] parent_list = [];
         parent_list ~= new A();
         parent_list ~= new B();

         foreach (item; parent_list) {
                 writeln(typeid(item));
         }
}
--------------------

With 2.068, it will output:

test.Parent
test.Parent

As far as I can tell, there is no way to know the actual type of 
each of the objects in the list to be able to print:

test.A
test.B

Are there any workarounds for this?

Also, this fails to compile when it doesn't look like it should:
--------------------
interface Parent {
         void method();
}

class A : Parent {
         void method() {}

         this() {}
}

class B : Parent {
         void method() {}
         void method2() {}

         this() {}
}

void main() {
         import std.stdio;

         Parent[] parent_list = [new A(), new B()];

         foreach (item; parent_list) {
                 writeln(typeid(item));
         }
}
--------------------


Thanks.


More information about the Digitalmars-d-learn mailing list