safer casts - take II

Yigal Chripun yigal100 at gmail.com
Tue May 13 12:08:34 PDT 2008


terranium wrote:
> Janice Caron Wrote:
> 
>> Could you be a bit more specific?
> 
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=71111
> 
> 
> my proposal would be to make cast safer 1) throw InvalidCastException
> on invalid cast 2) keep const
> 
> const_cast, dynamic_cast, static_cast, reinterpret_cast templates can
> be implemented using this safe cast, they can be inefficient and ugly
> - it's normal, because they normally should not be used.
> 
> This will break existing code a little 1) if(auto x=cast(X)y) will
> probably throw in a predicted location, workaround - when porting,
> replace cast with dynamic_cast template (which should be provided by
> standard library for porting legacy code) 2) won't compile if
> mutability is used - easy to fix.

You want the RTTI cast to throw on error. I'm personally a bit torn here
since on the one hand I do see your point and it is more "clean" for
some examples. on the other hand it adds a performance penalty the
others do not want. Casts shouldn't be normally used and if you do use
them then you should pay the performance price, right?
this current proposal suits everyone in that you can simply define a
template my_cast that will call the cast(T) operator and on null will
throw an exception.
maybe a helper template like this could be added to the proposal as well
since we already added the reinterpret_cast in a library form too.
so D will have two basic language level constructs and two additional
library helper templates:
built into the language:
cast(T)
cast!(T)
import std.cast for this: [the name is just an example, of course]
reinterpret_cast!(T)
strong_cast!(T) // like cast(T) only throws on error

I don't add this to the "official" proposal yet, this is still just some
thoughts not finalized into anything formal.
feel free to discuss this and propose names for the strong_cast!(T)
template.





More information about the Digitalmars-d mailing list