Implementing casting outside of the target struct

David Zhang via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 16 14:36:31 PDT 2017


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.


More information about the Digitalmars-d-learn mailing list