Call method if declared only

Simen Kjærås simen.kjaras at gmail.com
Fri Feb 28 09:49:53 UTC 2020


On Friday, 28 February 2020 at 09:25:58 UTC, Виталий Фадеев wrote:
> Yes. Thank !
> I read it.
> Problem is - OS has many messages + user messages... It mean 
> what interfaces like IKeyDown must me declared. All. Dream on 
> write less code...

So let's create a template for that:

interface IMessageHandler(alias msg) {
     mixin("LRESULT On"~__traits(identifier, msg)~"(WPARAM wParam, 
LPARAM lParam);");
}

And use it:

import core.sys.windows.windows;
import std.stdio;

class Base {
     LRESULT On(UINT message, WPARAM wParam, LPARAM lParam) {
         switch (message) {
             case WM_KEYDOWN:
                 if (auto that = 
cast(IMessageHandler!WM_KEYDOWN)this) {
                     return that.OnWM_KEYDOWN(wParam, lParam);
                 }
                 break;
             default:
         }
         return 0;
     }
}

class Button : Base, IMessageHandler!WM_KEYDOWN {
     LRESULT OnWM_KEYDOWN(WPARAM wParam, LPARAM lParam) {
         writeln("WM_KEYDOWN");
         return 0;
     }
}

unittest {
     Base b1 = new Base();
     Base b2 = new Button();

     writeln("Base:");
     b1.On(WM_KEYDOWN, 0, 0);
     writeln("Button:");
     b2.On(WM_KEYDOWN, 0, 0);
}

You'll still have to specify for each derived class which 
messages they handle, but no need to define hundreds of 
interfaces separately.

--
   Simen



More information about the Digitalmars-d-learn mailing list