Safer casts

Yigal Chripun yigal100 at gmail.com
Sun May 11 16:18:30 PDT 2008


Janice Caron wrote:
<snip>
if interpret_cast can be implemented by the user and it is quite
dangerous, than i think people who need that should implement that
themselves with union as you showed. no need for D to provide that
functionality by default.
I'm still not sure about constancy casts. but in order to provide the
minimal solution, I'd prefer cast!(T) to do constancy casts over adding
another construct for that. also, I don't like the static cast(), and it
might cause ambiguity problems. what is this good for?

open question: if this proposal does not provide a reinterpret_cast, can
we split the cast!(T) to perform either a type change /or/ a constancy
change?

int n = ...;
auto d1 = cast(double)n; //converts the n to double so 1 => 1.0
// below case uses the same bit pattern, exception on invalid double
// value
auto d2 = cast!(double)n;

same goes for classes with user defined cast and cast! operators.
downcast can be treated as a compiler pre-defined conversion from a
class to its derived classes. uses the cast(Derived) form and throws
exception on error.
constancy is performed via cast!(T).
pointers are cast with cast!(T)
so to convert const(int)* to const(long*) you'll need something like:
auto res = cast!(const(long*))cast(const(long)*)x;




More information about the Digitalmars-d mailing list