Casts and conversions done right

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Jul 21 00:29:21 PDT 2009


Daniel Keep wrote:
> 
> 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).

Wouldn't this by necessity have to be a built-in feature of the language?


> 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.

Recently, Julien Leclercq posted an enhancement request for Phobos 
entitled "'std.conv.to': check for a custom 'to' method in classes/structs".

     http://d.puremagic.com/issues/show_bug.cgi?id=3189

I think it would be a very good idea to make to!(T) *the* convention for 
built-in, standard library and user types. It would make for a unified, 
consistent approach to conversions:

     double x = 3.14;
     MyFloat y = 2.72;

     int i = to!int(x);
     int j = to!int(y);
     string s = to!string(x);
     string t = to!string(y);

Beautiful, no? :)

-Lars



More information about the Digitalmars-d mailing list