how can i use the derive-hierarchy at runtime for typechecking?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Sep 20 14:44:39 PDT 2007


Downs wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Just cast it.
> If you have class A { } and class B : A { }
> and A foo=new B;
> then you can do cast(B) foo and it will be non-null.
> On the other hand, if you do A bar=new A;
> and you do cast(B) bar, it will be null.
> 
> Here's a little utility function for this
> void ifIs(S, T)(S obj, void delegate(T) dg) {
>   auto casted=cast(T) obj;
>   if (casted) dg(casted);
> }
> 
> Use it like thus
> 
> ifIs(foo, (B whee) { /* do stuff with whee */ });
> 

And thanks to an oft-forgotten feature, you could shrink that down a little further to 
just a one-liner:

void ifIs (S, T) (S obj, void delegate(T) dg) {
   if (auto casted = cast(T) obj) dg(casted);
}

http://digitalmars.com/d/1.0/statement.html#IfStatement

-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list