Testing derived type

Kirk McDonald kirklin.mcdonald at gmail.com
Sat Jul 5 14:18:50 PDT 2008


Nick Sabalausky wrote:
> "Nick Sabalausky" <a at a.a> wrote in message 
> news:g4onj4$1cbf$1 at digitalmars.com...
>> I assume there's some way to do the following (D1 and Tango) without 
>> converting to and comparing strings, but...how?
>>
>> module modA;
>> class base {}
>> class derivedA : base {}
>> class derivedB : base {}
>> class derivedC : base {}
>>
>> module modB;
>> base[] array;
>> foreach(base elem; array)
>> {
>>    if(elem.toString[locatePrior(elem.toString, '.')+1..$] != 
>> derivedA.stringof)
>>    { /* do stuff */ }
>> }
>>
> 
> To clarify, what I'm looking for is this):
> 
> module modA;
> class base {}
> class derivedA : base {}
> class derivedB : base {}
> class derivedC : base {}
> 
> module modB;
> base[] array;
> foreach(base elem; array)
> {
>     // Do this without converting to and comparing strings
>     if(/* elem is not an instance of  'derivedA' */)
>     { /* do stuff */ }
> }
> 
> 
> 

Attempt to cast it to a derivedA. If it isn't actually an instance of 
derivedA (or of a subclass of derivedA), the cast will return null. 
(Just like dynamic_cast in C++.)

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list