Safer casts

Yigal Chripun yigal100 at gmail.com
Sun May 11 06:26:32 PDT 2008


Janice Caron wrote:
> 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.

another option would be to allow:
cast(const(T))x;
where you redefine the constancy of x and this would be subject to a
test that T is not a different type (except for constancy, of course).
that could simply be a syntax sugar for two separate semantic casts
(even if the compiler does it in one operation)
so, this would become:

const(int*) x = ...;
auto newX = cast(const(int)*)x;

the check is to take both types, remove all const/invariant and compare.
the result must be identical.
thus,
const(int*) => (int*) and const(int)* => (int)* which are identical.
put a different amount of stars, or replace int with long and the cast
fails.
I'm not sure if this is that important to add, since you can just use
two casts.

sprinkle this post with invariant where needed, to make this a full
proposal.

--Yigal



More information about the Digitalmars-d mailing list