Safer casts

Yigal Chripun yigal100 at gmail.com
Fri May 9 17:41:15 PDT 2008


I too do not like the proposed syntax. I'd suggest the following scheme:
1) convert: cast(foo)bar
2) reinterpret: cast!(foo)bar
3) constancy: cast(invariant), cast(mutable)
4) downcast: cast!(foo)bar

explanation:
all casts use the word "cast" so it's easy to grep for. more dangerous
casts use the "cast!" form. reinterpret and downcast both do the same
thing therefore there's no need to separate the two (both do not change
the actual memory). Constancy is cast explicitly with its own cast instance.

example of use:
invariant int a = ...;
double a = cast!(double)cast(mutable)(b);

the above removes invariance and then reinterprets the bit pattern to
double.

class B : A {}
class C : A {}
A b = new B;
C c = cast!(C)b; // c is null

cast! is more dangerous and thus can fail and return a null as in the
above example. OTOH, cast is safe and expected to always work, so if you
use cast instead of cast! to downcast, an exception will be thrown.

have I left anything out?

-- Yigal

PS - note that my proposal only adds the "cast!" form to D.
cast(invariant) is already defined in D, and cast(mutable) can be
replaced by cast(!invariant) although it's less readable IMO.



More information about the Digitalmars-d mailing list