Search code examples
ddmd

Get the parent of a class in D


How can I get the base type of a class from outside that class? I found the trait parent in the docs, but I'm not sure how to use it.

module test;
import std.stdio;

class A {}
class B : A { }

void main() {
    writeln(typeid(__traits(parent, B)));
    writeln(typeid(__traits(parent, test.B))); // try prefixing with module name
}

I would expect to get A in at least the second case, but this prints

void
void

Ideally I'd like to assign the base class of some class T to an alias and use that as I would any other type. For example:

alias T = __traits(parent, V);
T t = new T();

Solution

  • __traits(parent, ...) is about scopes. __traits(parent, B) is the test module. The documentation is too vague about this.

    std.traits.BaseClassesTuple is what you're looking for.

    As a general rule, look in std.traits first. The ugly __traits shouldn't come up in user code often.


    Some working sample code:

    module test;
    import std.stdio;
    import std.traits;
    
    class A {}
    class B : A { }
    
    void main() {
        writeln(__traits(parent, B).stringof); /* prints "module test" */
        alias Bases = BaseClassesTuple!B;
        writeln(Bases.stringof); /* prints "(A, Object)" */
        static assert(Bases.length > 0);
        alias T = Bases[0];
        auto t = new T;
    }