List of derived types?

Simen kjaeraas simen.kjaras at gmail.com
Thu Dec 16 05:55:53 PST 2010


d coder <dlang.coder at gmail.com> wrote:

> Greetings
>
> I need a way to know (using traits or other compile time constructs)
> all the types derived from a given type.
> Is it possible in D?

No.

> Is it possible to get a list of all the user-defined classes? I could
> use that to filter out the classes that I need.

No.


However, it is possible at run-time to iterate through all classes and
at that time compare them to the base class:

T[] getDerivedClasses( T )( ) if ( is( T == class ) ) {
     T[] result;
     foreach ( mod; ModuleInfo ) {
         foreach ( cls; mod.localClasses ) {
             if ( mod.name == "object" ) {
                 break;
                 }
             auto cls_base = cls;
             do {
                 if ( cls_base.name == T.classinfo.name ) {
                     if ( T tmp = cast(T)cls.create( ) ) {
                         result ~= tmp;
                     }
                 }
             } while ( ( cls_base = cls_base.base ) != Object.classinfo );
         }
     }
     return result;
}


-- 
Simen


More information about the Digitalmars-d-learn mailing list