rtti cast

Jarrett Billingsley kb3ctd2 at yahoo.com
Fri May 2 13:40:29 PDT 2008


"terranium" <spam at here.lot> wrote in message 
news:fvf93j$194u$1 at digitalmars.com...
> Pragma Wrote:
>
>> If you absolutely need an exception
>
> And who don't?

I don't.

I perform downcasts extremely rarely.  When I do, it's usually in code like:

if(auto y = cast(Y)x)
    ...
else
    // not a Y, try something else

That is, the code is only executed if the cast succeeds.

Furthermore, it's a lot easier and more efficient to have the cast return 
null and throw an exception _only if needed_ than to throw an exception and 
then have to catch it:

try
{
    auto y = cast(Y)x;
    ...
}
catch(CastException e)
{
    // not a Y, try something else..
}

For that matter, some languages (like C#) have both kinds of casts - one 
that throws an exception and one that doesn't.  Either can really be 
implemented in the other, but the null-returning kind is more basic and 
efficient. 





More information about the Digitalmars-d mailing list