Safer casts

Yigal Chripun yigal100 at gmail.com
Sun May 11 09:02:16 PDT 2008


Janice Caron wrote:
> 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.
I'm not sure your syntax can be used since those two words already have
a different meaning, wouldn't it create ambiguity in the language?
--Yigal
since i don't classify the casts as you do, I'm not sure I agree with
the above. didn't you yourself complain that cast(T) can remove
constancy by mistake and create bugs?
why would you allow cast!(T) to do just that?
anyway, I need to think more about that. I haven't arrived at a
conclusion yet, so I'd appreciate more examples/explanations.

Also, My definition was that cast() can change the memory while cast!()
doesn't. it seems you define them in reverse of that.


--Yigal



More information about the Digitalmars-d mailing list