is there any way to get a list of classes that inherit a class?

Simen kjaeraas simen.kjaras at gmail.com
Sun Feb 13 12:06:06 PST 2011


hyp <noreply at gmail.com> wrote:

>
> Hello,
>
> I know you can easily get the base class of some class in D. However is  
> there any way to get a list of classes that inherit a given class?
> I was reading around the docs, but couldn't find anything :/. But maybe  
> someone knows how to do it?

This question is probably better asked in digitalmars.D.learn.

As for the solution, this works:

TypeInfo_Class[] getSubClasses( Object o ) {
     typeof( return ) result;
     auto base = o.classinfo;

     foreach ( m; ModuleInfo ) {
         foreach ( c; m.localClasses ) {
             auto a = c;
             while ( a && a != base ) {
                 a = a.base;
             }
             if ( a == base ) {
                 result ~= c;
             }
         }
     }

     return result;
}


class A {}
class B : A {}

void main( ) {
     writeln( getSubClasses( new A() ) );
}

Do note however, that templated classes do not show up in this search.

-- 
Simen


More information about the Digitalmars-d mailing list