the cast mess

grauzone none at example.net
Mon May 18 02:23:53 PDT 2009


I'd propose to remove cast(T) from the language, and replace it by 
several special template functions in object.d:
- a "B cast!(A, B)(A x);", which _always_ does the most safe thing, it 
would allow the following: casting between objects and interfaces, all 
implicit casts allowed by the language, and possibly use declared opCast 
from user data types
- a constCast() to fight with thew const/immutable/shared mess
- a lossyCast() for numeric conversions
- possibly a checkedCast() for numeric conversions, which dynamically 
checks for overflows and throws an exception on failure
- reinterpretCast(), the most evil thing that can exist

Note that some casts need compiler support. Like float<->int conversions 
is done with special CPU instructions on the lowest level. To allow 
implementation of the cast functions in pure D code, these instructions 
can be provided as intrinsic functions. (Just like bit scan or port I/O 
instructions.)

The worst thing about the current cast(T) operator is that it easily 
allows reinterpret cast. This is SO NOT SAFE! Especially with arrays, it 
doesn't do something what the user expects. It's a hidden reinterpret 
cast. This really should be changed.

(Oh btw., with my proposal, you could use cast!(T) for proper array 
casts, which allocate a new array, casts each element with cast!(T), and 
return it; or you could use reinterpretCast() to get the current behavior.)



More information about the Digitalmars-d mailing list