Casts and conversions done right
Daniel Keep
daniel.keep.lists at gmail.com
Mon Jul 20 10:01:20 PDT 2009
Lars T. Kyllingstad wrote:
> 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.
>
> ...
>
> 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
This is a bit of a bug-bear of mine, too. I originally wrote Tango's
to!(T) template with the express condition that it would only ever
perform value conversions.
We could probably write another template called reinterpret!T or
recast!T or something that explicitly takes a collection of bits and
reinterprets them as another type (ie: the *cast(int*)&pi case).
If we also added, say, objcast!T that only accepted object types, then
we could lock cast(T) away in a box and electrocute the lid. :D
As for people wanting to control the rounding mode, etc., that's what
functions are for. My personal position is that stuff like to!T should
exist to do perform a sane default conversion; if you want more control,
you should use a more specialised function.
More information about the Digitalmars-d
mailing list