Thread overview
Re: rtti cast
May 08, 2008
terranium
May 08, 2008
Janice Caron
May 08, 2008
terranium
May 08, 2008
Jarrett Billingsley Wrote:

> I've only ever used downcasts in D as a replacement for Java's "instanceof", where it's just a simple typecheck.

cast is not a typecheck, it's a type conversion.
May 08, 2008
2008/5/8 terranium <spam@here.lot>:
>  cast is not a typecheck, it's a type conversion.

In C++, there is a difference between a regular cast and a
dynamic_cast. The expression dynamic_cast<T>(x) performs a run-time
type check and type conversion. See
http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/topic/com.ibm.vacpp6m.doc/language/ref/clrc05keyword_dynamic_cast.htm

dynamic_cast<T>() returns a null pointer of type T if the cast fails. Users of dynamic_cast<T>() are therefore required always to check the return value for null. This is not an indication of a bug - it is designed behavior.

Thus, in C++

(1) traditional cast is not a typecheck, it's a type conversion
(2) dynamic cast is a a runtime type check

Unfortunately, D's cast(T)x behaves exactly like C++'s dynamic_cast<T>(x) when it comes to casting up and down a class heirarchy. D only has one kind of cast, and it does both jobs. So Jarrett is using D's casts correctly, /but/ D's casts are themselves flawed. The "one cast that does everything" ideology is just a tool for making bugs.
May 08, 2008
Janice Caron Wrote:

>
> (1) traditional cast is not a typecheck, it's a type conversion
> (2) dynamic cast is a a runtime type check
> 
Typecheck just determines whether an object can be cast to the target type, so this is boolean function similar to Java's instanceof and C#'s is. dynamic cast does a type conversion and applies a typecheck during the conversion and the result depends on whether the typecheck succeeded. It was noted that for failed typecheck for pointer type null is returned and for failed typecheck for reference type bad_cast is thrown. And D reference types are very similar to those of C++ (at least in syntax :) ) except that C++ reference can't be changed after initialization.