Casts and conversions done right
Daniel Keep
daniel.keep.lists at gmail.com
Tue Jul 21 03:24:50 PDT 2009
Lars T. Kyllingstad wrote:
> Daniel Keep wrote:
>>
>> ...
>>
>> 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?
Why would it?
ref T recast(T,U)(ref U v) if( T.sizeof <= U.sizeof )
{
return *cast(T*)&v;
}
Or something similar should be possible.
>> ...
>>
>> 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
Tango already does this. Actually, it goes a few better than that: any
user-defined type can have to(T), to_{type_name} or to{TypeName} members
that it will use to do conversions as well as static from(T),
from_{type_name} or from{TypeName} methods to do reverse conversions.
> 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
Again; why do you think I wrote Tango's to(T) template in the first
place? :D
More information about the Digitalmars-d
mailing list