testing if an instance is a subclass of a given class

downs default_357-line at yahoo.de
Tue Sep 16 23:02:57 PDT 2008


downs wrote:
> Paul Dufresne wrote:
>> And would it be possible to write an isSubclass function in D based on this test...
>> I don't see how I would pass the Class for the test... what come in mind naturally would be:
>> bool isSubclass (Class C, Object o){
>>   if (cast (C o) then return true else return false;
>> }
>>
>> but the Class type does probably not exist ... does it?
> 
> Close.
> 
> bool isA(T)(Object obj) {
>   return (cast(T) obj)?true:false;
> }
> 
> ..
> 
> class A { }
> class B : A { }
> 
> A x = new B;
> 
> if (isA!(B)(x)) { } else { }
> 
> Note however, that this is an exercise in redundancy, as it is almost exactly the same as "if (cast(B) x)".
> 
> I really recommend you use that instead.

In fact, there's a nifty idiom that exploits the fact that you can create a variable in an if statement ..

A x = new B;

if (auto xAsB = cast(B) x) { /* do op on xAsB */ }


More information about the Digitalmars-d-learn mailing list