safer casts - take II
Jason House
jason.james.house at gmail.com
Tue May 13 15:12:33 PDT 2008
Long ago in one of the const threads, a few people settled on cast(break const) for what I think you're calling cast!(T). I like that better than using template syntax to mean less safe.
Yigal Chripun Wrote:
> since the other thread got completely off-topic and lost any connection
> to the original discussion, here's a new clean thread, that will
> hopefully summarize the previous discussion and present the latest
> proposal so that hopefully more people join the debate without the need
> to go through all the previous posts (164 posts!).
>
> Here goes:
>
> the proposal is for a safer cast that will _replace_ the current cast.
> this is important both for a consistent syntax and to prevent subverting
> the system with the old style cast.
>
> there are there forms of cast:
> (a) cast(T)something
> (b) cast!(T)something
> (c) reinterpret_cast!(T)
>
> there is no need for language support for (c) since this can be
> implemented via a union and this is exactly what this library template
> does. the only reason for this is to have a standardized name. unless
> the user really knows what he's doing this should be avoided, since this
> is the most dangerous form of cast.
>
> goals of this design:
> 1. you can search/grep for all casts in your code.
> 2. constancy is cast explicitly so no more casting an invariant T to a
> mutable U in one cast. this prevents bugs.
>
> (a) will do would you'll expect in the common case. while (b) is for
> more "dangerous" casts. it can also be defined in all forms
> (implicit/explicit) by the user while (b) isn't.
>
> if T is a class then (a) uses RTTI cast (down casting) or a user defined
> conversion, otherwise (a) will do plain conversions like the current
> cast does.
> (b) is used for constancy casts and the specific use case of casting
> pointers to void. (more specific cases could be added in the future)
>
> for c++ people this translates to:
> (a) (T is a class) ? dynamic_cast : static_cast
> (b) const_cast
> (c) reinterpret_cast implemented in library
>
> also note that cast(T) for classes will return null on failure just
> like in current D.
>
> questions?
More information about the Digitalmars-d
mailing list