Re: Implementing casting outside of the target struct

2017-03-16 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, Mar 16, 2017 at 09:36:31PM +, David Zhang via Digitalmars-d-learn 
wrote:
> Hi,
> 
> I have two structs and want to cast between them. The cast is
> generalizable, so I want to keep it outside of the structs themselves
> (I'll be adding more later). How can I do this?

AFAIK, the opXXX() methods must be defined inside the aggregate in order
to have any effect, i.e., opCast is treated like operator overloading,
for which UFCS does not work.

Maybe rename opCast to something else, say convert(), and add new opCast
methods to the structs that forward to convert()?


T

-- 
Try to keep an open mind, but not so open your brain falls out. -- theboz


Implementing casting outside of the target struct

2017-03-16 Thread David Zhang via Digitalmars-d-learn

Hi,

I have two structs and want to cast between them. The cast is 
generalizable, so I want to keep it outside of the structs 
themselves (I'll be adding more later). How can I do this? I've 
tried the following so far:


struct Event {
EventID id;
ubyte[32 - EventID.sizeof] payload;
}

struct WindowCreateEvent {
enum id = EventID.windowCreate;

version (Windows) {
import core.sys.windows.windows;
HWND windowHandle;
}
}

T opCast(T, K)(auto ref K e) {
import core.stdc.string: memcpy;

auto result = Event(e.id);

memcpy(result.payload.ptr, cast(void*) & e, K.sizeof);

return result;
}

The compiler seems to want to convert the two structs bit-by-bit. 
How can I make it use the module-scoped override? Thanks.