Safer casts

BCS BCS at pathlink.com
Fri May 9 10:20:23 PDT 2008


Janice Caron wrote:
> (*) Use RTTI to cast up and down the class heirarchy. In C++, this
> would be dynamic_cast<T>(x). For D, I suggest two things. Firstly, the
> cast:
> 
>     class!(T)(x)
> 
> to do that actual upcast or downcast - but RTTI dynamic casts can
> fail, so the question arises: What should we do if the cast fails?
> Should we return null, or should we throw an exception. My view is
> that we should throw an exception, but also introduce a new construct
> to test whether or not the cast would be possible in the first place:
> 
>     is!(T)(x)
> 
> which returns bool. is!(T) would be like Java's instanceof. Thus, one
> could write
> 
>     void f(A a)
>     {
>         if (is!(B)a)
>         {
>             B b = class!(B)(a);
>             /*...*/
>         }
>         else if (is!(C)a)
>         {
>             C c = class!(C)(a);
>             /*...*/
>         }
>     }
> 
> etc.
> 

The major issue I have with this is that the construct that actually 
does the downcast MUST also do the type check. Therefor it gets done 
twice and this is  a bit of a performance issue. (and performance snobs 
will start finding way to skip the second test (like your union) and 
then get it wrong.)

I'd rather see a testClass!(T) version that acts exactly like the 
current cast and a isClass!(T) that acts like your class!(T).



More information about the Digitalmars-d mailing list