Why not move cast to the standard library?

Jeremie Pelletier jeremiep at gmail.com
Thu Sep 24 13:25:35 PDT 2009


downs wrote:
> Jeremie Pelletier wrote:
>> downs wrote:
>>> Jeremie Pelletier wrote:
>>>> grauzone wrote:
>>>>> Andrei Alexandrescu wrote:
>>>>>> downs wrote:
>>>>>>> Andrei Alexandrescu wrote:
>>>>>>>> downs wrote:
>>>>>>>>> With all the neat template tricks we have in 2.0, and since we're
>>>>>>>>> widely redefining the syntax anyway, why not deprecate the current
>>>>>>>>> cast syntax and move it into object.d as a library function?
>>>>>>>>>
>>>>>>>>> So instead of cast(Foo) bar; you would say cast!Foo(bar); .. save
>>>>>>>>> on a
>>>>>>>>> keyword and demonstrate language power at the same time.
>>>>>>>>>
>>>>>>>>> What sez ye?
>>>>>>>> What would the implementation look like?
>>>>>>>>
>>>>>>>> Andrei
>>>>>>> Unions, and LOTS of static ifs. :)
>>>>>> Unions won't work for casting class objects and interfaces because
>>>>>> those do pointer adjustments. I think cast must be a primitive.
>>>>> When casting interfaces and objects, the primitive cast just calls
>>>>> into runtime (functions like _d_dynamic_cast etc.). I don't see a
>>>>> reason why cast implemented as templated function couldn't call those
>>>>> runtime functions directly.
>>>>>
>>>>>> Andrei
>>>> What about cast(int) or cast(string) and whatnot then? You'd have
>>>> cast!A(B) for classes and cast(int) for values, that would be backwards.
>>>>
>>>> Jeremie
>>> What about cast!int could _not_ be done as a function?
>> I don't want to call into functions for simple value casts. If I want
>> safe casts I use to!int. It may get inlined in release code, but think
>> of the debug overhead it would generate.
>>
>> The current way is great as it is, cast() for straightforward unsafe
>> casting and to!(T)() for safe casting. This is exactly what makes D
>> attractive to me, the choice between safe and unsafe alternatives.
> 
> What debug overhead?
> 
> With current casts, all the logic is in the compiler - where you can't get at it. Moving it into the library can only make this better.
> 
> There is nothing about cast that I can see that requires dedicated compiler assistance.
> 
> Furthermore, consider it a testcase - if a trivial function like that isn't inlined, _something_ is wrong :)

Compile with -debug -unittest -g and you get no inlines whatsoever, even 
const values aren't inlined, when I run such an executable in windbg the 
code cursor actually goes to the declaration of enums and other constants.

A lot of casts are just type reinterpretations, with a few semantics 
behind float to int conversions. I wouldn't give away the convenience of 
cast() to force everything through to!(T)(). I use cast() for most cases 
where I don't need anything special, and to!(T)() when I need some 
specific semantics. It also makes such cases much easier to notice when 
reading code.



More information about the Digitalmars-d mailing list