Safer casts

Janice Caron caron800 at googlemail.com
Fri May 9 22:12:59 PDT 2008


On 10/05/2008, Dee Girl <deegirl at noreply.com> wrote:
> With much interest I followed this thread. Forgive my ignorance, but I can not understand one thing. Could this functionality be implemented as library functions all using the built in cast?

Not really, since part of the proposal is that

   const c = new C;
   auto d = cast(C)c; // ERROR - cast cannot remove constancy

should not compile. I see ruling this out as an important part of
const correctness.

If you make it optional (e.g. have some sort of template,
static_cast!(T)), then people are just going to write "cast" instead
of "static_cast!" because (a) it's shorter, and (b) the programmer's
inherent belief that everything they write is bug free. That's exactly
what happens in C++.

Ruling out the ability of cast(T) to remove constancy is exactly the
same philosophy as that of not allowing const objects to be passed to
mutable functions.

Naturally, there must be a way of removing constancy if you really,
really want to, because D is a systems programming language. That's
the reason Yigal suggested cast(mutable), and I suggested
cast(!const). Either way, it tells the compiler "I'm doing this on
purpose".



More information about the Digitalmars-d mailing list