Safer casts

Janice Caron caron800 at googlemail.com
Sun May 11 08:09:25 PDT 2008


On 11/05/2008, Yigal Chripun <yigal100 at gmail.com> wrote:
> Actually, we got it slightly wrong:
>  since D defines removal of invariance as undefined behavior and since casting with constancy does not convert the value but rather changes the type tag of the value, it would be more appropriate to use the "cast!" form, IMO.

Hmmm. Perhaps. But then you lose the distinction between const_cast
and reinterpret_cast. With cast!() acting as reinterpret_cast, I can
do:

    void foo(Something x)
    {
        auto y = cast!(Anything)x;
        ...
    }

and it would always succeed, and you can't say "unless there's a
change of constancy" in this case, because the before and after might
have completely different memory layouts, so there'd be no way even to
tell whether or not that had happened.

I can see that const_cast and dynamic_cast could share the same
syntax, but I really don't see how reinterpret_cast could double up
with /anything/ else.

So maybe that brings us to this:

    cast(T)x // dynamic_cast
    cast!(T)x // reinterpret_cast
    static cast(T)x // static_cast
    const cast(T)x // const_cast

That does have a certain appeal to it.



More information about the Digitalmars-d mailing list