safer casts - take II

Dee Girl deegirl at noreply.com
Tue May 13 12:13:40 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.

Maybe the way it should work is this. The language provides primitives. Library constructs from primitives. But cast that throws is not good primitive. Because you need expensive operation to implement cast that returns null on failure. A better primitive is cast that returns null. You can implement cast that throws in a library. 

One more opinion I have. The pattern in Java with if (a isa Type) { Type t = (Type) a; ... } is very clunky. It is not inefficient. Because Java compilers all have special case for the sequence (peephole optimization). But it is verbose programming style with duplication. If you use cast that throws in D then you are forced in that pattern. Another reason cast that throws is not good. Thank you, Dee Girl



More information about the Digitalmars-d mailing list