On Saturday, 15 January 2022 at 23:15:16 UTC, JN wrote:

Is there some way I could improve this with some D features? My main gripes with it are:


Managed to dramatically simplify it to 10 lines of code with variadic templates.

```d
import std.stdio;

struct Event(T...)
{
    void function(T)[] listeners;

    void addListener(void function(T) handler)
    {
        listeners ~= handler;
    }

    void emit(T args)
    {
        foreach (listener; listeners)
        {
            listener(args);
        }
    }
}

void onResize(uint newWidth, uint newHeight)
{
    writefln("Resized: %d %d", newWidth, newHeight);
}

void main()
{
    Event!(uint, uint) windowResizeEvent;
    windowResizeEvent.addListener(&onResize);

    windowResizeEvent.emit(1000, 2000);
}
```

I am very happy with this solution.

Reply via email to