Safer casts

Janice Caron caron800 at googlemail.com
Fri May 9 21:45:59 PDT 2008


On 10/05/2008, Yigal Chripun <yigal100 at gmail.com> wrote:
> 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

Your proposal is better than mine, but I think I can improve it even more:

1) convert: cast(Foo)bar
2) reinterpret: cast!(Foo)bar
3) constancy: cast(invariant)bar, cast(!const)bar
4) downcast: cast(Foo)bar

There are just two differences. I suggest cast(!const) to remove
constancy, because cast(mutable) could be ambiguous if there happened
to be a type called "mutable" (unless you're suggesting "mutable" be a
reserved word, but Walter would never allow that).

Downcasting isn't particularly dangerous, providing you always check
the return value, so no exclamation mark needed there.

The important point about this proposal is that the following will
/not/ compile:

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

But this will

    const c = new C;
    auto d = cast(!const)c; // OK

Likewise with downcasting

    void foo(in A a)
    {
        B b = cast(B)a; // ERROR - cast cannot remove constancy
        if (b !is null) ...
    }

but the following would be OK

    void foo(in A a)
    {
        B b = cast(B)cast(!const)a; // OK
        if (b !is null) ...
    }

although of course, what you probably should be doing is really:

    void foo(in A a)
    {
        const B b = cast(const B)a; // OK
        if (b !is null) ...
    }



More information about the Digitalmars-d mailing list