Safer casts

Yigal Chripun yigal100 at gmail.com
Mon May 12 16:10:22 PDT 2008


Simen Kjaeraas wrote:
> Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> 
>> Now, if you casting to be able to rebind ptr, then I think you would need
>> some crazy casting like you stated.
>>
>> -Steve
> 
> Actually, I had no other intent than to see if I could break the system.
> For a better (or worse, mayhaps) version: const(C*)* (or whatever, really)
> to const(invariant(C)*)*. For this, I'd prefer Janice's suggestion of
> const cast, as I understand it:
> 
>   const(C*)* foo;
> 
>   cast(const(invariant(C)*)*)foo; // error, cast can't change constancy
> 
>   const cast(const(invariant(C)*)*)foo; // works like a charm
> 
> The const cast looks good to me, whereas what I used in the last example
> was downright ugly. Casting to a different constancy should be one cast,
> not first making it all mutable, and then put const back in there.
> 
> -- Simen

if I'm not mistaken, the other example was both a cast of constancy and
of type. that needs two casts (that's one of the main principles of this
proposal). in the latest version of this proposal, the above would be:

const(C*)* foo;
cast!(const(invariant(C)*)*)foo; // works like a charm

a cast without the ! is not defined for constancy casts, so the compiler
would err and suggest using cast! instead (maybe with a message than
warn the user that this can be dangerous)



More information about the Digitalmars-d mailing list