Safer casts

Janice Caron caron800 at googlemail.com
Sun May 11 05:19:21 PDT 2008


On 11/05/2008, Simen Kjaeraas <simen.kjaras at gmail.com> wrote:
> On Sat, 10 May 2008 07:59:23 +0200, Janice Caron <caron800 at googlemail.com>
> wrote:
>
> > 1) convert or downcast: cast(Foo)bar
> > 2) reinterpret: cast!(Foo)bar
> > 3) constancy: cast(invariant)bar, cast(!const)bar
> >
>
>  For 3), what if I want to cast const(int*) to const(int)*?
> cast(const(int)*)cast(!const)foo?

Wow, we're back on topic again! Woo hoo!

Good question.

My first thought would be

    const(int*) newPtr = cast(!const)oldPtr;

that is, remove all the constancy, then put it back again. Another
possibility is:

    auto newPtr = cast(const(int)*)cast(!const)oldPtr;

which is exactly what you suggested. But neither are particularly
ideal, so it looks like an ammendment to the proposal is in order. So
my new suggestion would be, to remove only /part/ of the constancy,
one of the following:

    cast(!const, T)x
    cast(T, !const)x

Whichever people like best. A third possibility would be to (almost)
follow in the footsteps of C++, with

    const cast(T)x

which I kinda like, except that it makes specifying T mandatory, when
often you wouldn't need to.



More information about the Digitalmars-d mailing list