Getting a list of child classes
Another form of runtime information available in D is a list of all classes in the program. Using this information, we can achieve tasks that will be impossible at runtime, such as getting a list of all child classes of a particular class. A potential use of this capability will be to load game objects, defined as classes inheriting a common base, from an XML file at runtime.
How to do it…
Let's execute the following steps to get a list of child classes:
Get the
typeid
of the parent class you're interested in.Loop over
ModuleInfo
with theforeach
loop.Loop over the
localClasses
member of each loop value.Add recursion if you want to get all descendants, including the children's children.
The code is as follows:
ClassInfo[] getChildClasses(ClassInfo c) { ClassInfo[] info; foreach(mod; ModuleInfo) { foreach(cla; mod.localClasses) { if(cla.base is c) info ~= cla; } } return info; } class A {} class B : A...