www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Casting random type to random struct - is this a bug?

reply "rumbu" <rumbu rumbu.ro> writes:
struct S { int a, b; }
auto s = cast(S)10;
//compiles and sets s.a to 10.

It works also for any other type, if the structure contains a 
member of that type in the first position.

Is this normal behaviour?
Jul 15 2015
next sibling parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 7/15/15 11:45 AM, rumbu wrote:
 struct S { int a, b; }
 auto s = cast(S)10;
 //compiles and sets s.a to 10.

 It works also for any other type, if the structure contains a member of
 that type in the first position.

 Is this normal behaviour?
I would say this is a bug. As far as I know, it's not defined in the spec. -Steve
Jul 15 2015
parent Daniel =?UTF-8?B?S296w6Fr?= <kozzi dlang.cz> writes:
On Wed, 15 Jul 2015 11:57:01 -0400
Steven Schveighoffer <schveiguy yahoo.com> wrote:

 On 7/15/15 11:45 AM, rumbu wrote:
 struct S { int a, b; }
 auto s = cast(S)10;
 //compiles and sets s.a to 10.

 It works also for any other type, if the structure contains a
 member of that type in the first position.

 Is this normal behaviour?
I would say this is a bug. As far as I know, it's not defined in the spec. -Steve
It is defined: Casting a value v to a struct S, when value is not a struct of the same type, is equivalent to: S(v)
Jul 15 2015
prev sibling parent reply Daniel =?UTF-8?B?S296w6Fr?= <kozzi dlang.cz> writes:
On Wed, 15 Jul 2015 15:45:43 +0000
"rumbu" <rumbu rumbu.ro> wrote:

 struct S { int a, b; }
 auto s = cast(S)10;
 //compiles and sets s.a to 10.
 
 It works also for any other type, if the structure contains a 
 member of that type in the first position.
 
 Is this normal behaviour?
Yes, this is OK If you need to cast against diferent types you can try pointers: import std.stdio; struct S { ubyte a; ubyte b; } void main() { ushort m = 65535; auto s = *(cast(S*)&m); writeln(s); }
Jul 15 2015
parent "rumbu" <rumbu rumbu.ro> writes:
On Wednesday, 15 July 2015 at 15:58:17 UTC, Daniel Kozák wrote:
 On Wed, 15 Jul 2015 15:45:43 +0000
 "rumbu" <rumbu rumbu.ro> wrote:

 struct S { int a, b; }
 auto s = cast(S)10;
 //compiles and sets s.a to 10.
 
 It works also for any other type, if the structure contains a 
 member of that type in the first position.
 
 Is this normal behaviour?
Yes, this is OK If you need to cast against diferent types you can try pointers:
In fact I'm trying to overload the cast operator in this case, I was surprised about the default casting since I didn't find any reference to this behaviour, nor in TDPL, nor online. Since UFCS is not allowed in operator overloading I wonder if this is possible.
Jul 16 2015