Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Get the typeid of the parent class you're interested in.

  2. Loop over ModuleInfo with the foreach loop.

  3. Loop over the localClasses member of each loop value.

  4. 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...