Casting Structs

Paul D Anderson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 31 17:01:05 PDT 2014


On Saturday, 31 May 2014 at 22:34:45 UTC, Timon Gehr wrote:
> On 06/01/2014 12:25 AM, Ali Çehreli wrote:
>>>
>>> dec10 little = cast(dec10(bingo));
>>
>> You meant cast(dec10)(bingo).
>>
>>> assert(little == dec10("123.45"));
>>>
>>> Is this expected behavior?
>>>
>>> Paul
>>>
>>
>> That is surprising. I've discovered that if the template has 
>> members
>> that depend on a template parameter than the code fails to 
>> compile. I
>> think it should fail to compile in other cases as well because 
>> a
>> separate instantiation of a template is a separate type 
>> potentially with
>> completely different invariants.
>
> This behaviour is independent of templates. Struct values of 
> the same size can be reinterpret-cast to each other this way 
> even if their types are completely unrelated.
>
>
> struct A{
>     int a,b;
> }
> struct B{
>     long x;
> }
>
> void main(){
>     auto a=A();
>     auto b=cast(B)a;
> }

So, although this works it is undocumented and will probably be 
modified at some point. I won't use it and I'll file a bug report 
if I can't find one that covers it already. Thanks for your help.


More information about the Digitalmars-d-learn mailing list