digitalmars.D.learn - Implementing casting outside of the target struct
- David Zhang (24/24) Mar 16 2017 Hi,
- H. S. Teoh via Digitalmars-d-learn (9/14) Mar 16 2017 AFAIK, the opXXX() methods must be defined inside the aggregate in order
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.
Mar 16 2017
On Thu, Mar 16, 2017 at 09:36:31PM +0000, 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
Mar 16 2017