Casts and conversions done right

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Mon Jul 20 02:48:38 PDT 2009


The subject of casts has come up in various forms now and then, and with 
D2 nearing completion (or whatever you'd like to call it) I think it 
should be discussed properly.

Basically, we can divide (explicit) casts into two groups: safe and 
unsafe. The safe ones include

   - checked base-to-derived casting of class references
   - checked casts between struct types
   - numeric conversions

while the unsafe are things like

   - pointer reinterpretation
   - casting away constness
   - cast(public), cf. dsimcha's recent proposal

There are probably others I have forgotten. It pains me that I can use 
the same keyword to do these two things:

   double pi = 3.14;
   int i = cast(int) pi;
   int j = *cast(int*) π

The former is very common and ought to be done using some (library) 
function with a specific rounding mode, not with a cast. The spec 
doesn't even say how numbers are rounded when cast is used.

The latter is a very unsafe operation, which should of course be allowed 
in a language like D, but it should be clearly marked as unsafe.


Instead, I propose the above operations be written like this:

   int i = to!int(pi);    // The to function already exists in std.conv
   int j = cast!int(pi);

I've never liked the syntax of cast expressions in D -- they look like 
nothing else in the entire language -- and changing it like this would 
make sure no invalid or dangerous casts are left lying around in old 
code causing trouble.

What do you think?

-Lars



More information about the Digitalmars-d mailing list