Safer casts

Janice Caron caron800 at googlemail.com
Fri May 9 03:25:32 PDT 2008


2008/5/9 terranium <spam at here.lot>:
> and I like existing cast keyword, it's short enough to write and long enough to spot.

I like it too. But it has its disadvantages. For example, you might
write a dynamic cast as

    void f(in A a)
    {
        B b = cast(B) a;
        if (b !is null)
        {
            /* ... */
        }
        /*...*/
    }

and it would compile. Unfortunately, you have just accidently cast
away const, and that kind of bug is hard to spot. But replace it with

    void f(in A a)
    {
        if (is!(B)(a))
        {
            B b = class!(B)(a);
            /* ... */
        }
        /*...*/
    }

and you have a compile-time error, because class!(T) cannot change
const.into mutable.

So I guess there's a tradeoff between "nice" syntax, like cast(T), and
"safe" syntax. I'm just wondering if we should err on the side of safe



More information about the Digitalmars-d mailing list