Type functions example printing class hierarchy

Stefan Koch uplink.coder at googlemail.com
Fri Aug 21 16:19:36 UTC 2020

Hi there,

In a previous thread I talked about how pattern-matching is 
expressions are a pain to implement for type functions.
So I've taken the liberty to add an additional __trait to get the 
super type
Below is an example of how it might be used to visualize a class 
class A {}
class B : A {}
class C : A {}

string class_hierarchy(alias T)
     string result;

     alias super_type;
     // for now this is a typefunction-only __trait
     super_type = __traits(getSuperType, T);
         result ~= T.stringof ~ " -> " ~ super_type.stringof ~ 
         T = super_type;
         super_type = __traits(getSuperType, T);

     return result;

pragma(msg, "class_hierarchy(A): \n", class_hierarchy(A));
pragma(msg, "class_hierarchy(B): \n", class_hierarchy(B));
pragma(msg, "class_hierarchy(C): \n", class_hierarchy(C));

Of which the output is:

A -> Object

B -> A
A -> Object

C -> A
A -> Object

If there any questions about how this works please fire away.

Cheers, Stefan

PS. the addition of __traits(getSuperType) added 90 lines of code.
I think that's a worthwhile treat-off

More information about the Digitalmars-d mailing list