the cast mess

Don nospam at nospam.com
Mon May 18 02:09:10 PDT 2009


Vladimir Panteleev wrote:
> Hello digitalmars.D,
> 
> I'm concerned about the cast() situation with D. Right now, we use the same keyword and syntax to do three different things:
> 
> 1) The obvious plain-old-data cast (casting one pointer type to another, structures, etc.)
> 2) Type conversion casts (casting floats to ints)
> 3) Dynamic casts for classes (may result in null)
> (There may be more magic going on behind the scenes when e.g. casting between arrays with different element sizes - a proposal I saw some time ago to replace start/length with start/end would get rid of that)

4) removing const/immutable.

> 
> I attached a small program demonstrating a few uses of cast that may have unexpected results for new users. 
> 
> I'd like to ask: am I the only one who thinks that this inconsistent behavior of one of the language's base features sticks out like a sore thumb?
> I can see where this mess is coming from - the first two are from C, and the third is from the more dynamic languages (C++ has dynamic_cast but it's a separate language construct). I'm not aware of a language that abuses the same cast operator for such varying effects.
> Someone doing a code review will have to put in extra effort to tell apart safe casts from unsafe ones.
> In a metaprogramming context, nothing can be said about "cast(T)x" - whether it's type-safe, what overheads will it incur, etc.
> 
> I have the following suggestions to remedy the problem. They're probably too drastic even for D2, so even if they'd get accepted - probably for D3:
> 
> 1) Use the cast() keyword/syntax only to change the compiler's representation of the type. The source and target types must be of the same size. Practically it would be the same as *cast(T)(&x) with the current system, except with the additional size check. The compiler should issue a warning when previous versions would have performed data conversion.
> 
> 2) Move all "magic" value type conversions (float => int etc.) to intrinsic functions declared in the standard library.
> An additional argument for this move is that, IMO, taking the integer part of a floating-point number should be as accessible as rounding the number to the nearest integer, or any other float=>int conversions (trunc/ceil/etc.)

Personally, I _hate_ the fact that you can cast a float to an int. It's 
pretty amazing to me that Intel has done three different hardware 
modifications to get around a careless decision in the original C spec.


> 3) Switch to a new syntax for dynamic_cast-style casts. I propose the "c is T" syntax, which should function identically to the current "cast(T)c" and is much more readable.
> 
> Alternatively, we could bring back C-style casts for safe and "magic" type conversions (points 2 and 3), and leave cast() (or rename it to something scarier) for unsafe "reinterpret" casts.
> 



More information about the Digitalmars-d mailing list