Getting and using class hierarhy information in runtime

Adam D. Ruppe destructionator at gmail.com
Thu Feb 13 20:04:23 PST 2014


On Friday, 14 February 2014 at 03:48:13 UTC, Uranuz wrote:
>        {   if( exc.inheritsOrIs(type) )  //Checking type of


This function is basically the same as the cast function in 
druntime. Look for _d_isbaseof in the file 
dmd2/src/druntime/src/rt

https://github.com/D-Programming-Language/druntime/blob/master/src/rt/cast_.d#L115


You could literally call that function:

class Foo {}
class Bar : Foo {}
class Baz : Bar {}
class Test {}

// declare the function so we can access it (as an internal 
druntime
// function, thee is no import to provide it, but we can call it 
anyway)
extern(C) int _d_isbaseof(ClassInfo oc, ClassInfo c);

void main() {
         Foo f = new Bar;
         Foo z = new Baz;

         import std.stdio;

          // here's how to use it. f is a Bar which is a Foo, but 
not a Baz
         writeln(typeid(f)._d_isbaseof(typeid(Bar))); // 1
         writeln(typeid(f)._d_isbaseof(typeid(Baz))); // 0
         writeln(typeid(f)._d_isbaseof(typeid(Test))); // 0

         // z is a Baz which is a Bar and a Baz
         writeln(typeid(z)._d_isbaseof(typeid(Bar))); // 1
         writeln(typeid(z)._d_isbaseof(typeid(Baz))); // 1
}


typeid is the same as classinfo, it just gets that info. So the 
left side in your case would be the exception, and the right side 
would be the key in your associative array.

If it returns one, you have a match and can do ahead and call it.


More information about the Digitalmars-d-learn mailing list