On Thu, Dec 01, 2016 at 11:51:19PM +0000, Payotz via Digitalmars-d-learn wrote:
> So, to give context, I am trying to make an event manager for a game
> I'm making.
> I was writing the "register()" method so I ran into a problem.
> The register method will take in delegates as an argument, but those
> delegates have varied arguments themselves, so I can't really put
> anything there. I know that it's got something to do with templates so
> I tried my hand in it and came up with this:
> void registerEvent(string event_name,T...)(T delegate() dg);
> I know there's something missing in the way I did it, so I'll be glad
> for you folks to tell me what I'm missing.
> And for the second part of the question, I can't seem to make a
> Dynamic Array where I could store the delegates taken in the
> "registerEvent" method.  Closest thing I have gotten to is this:
> private void delegate(T)(T args)[string] event;
> which resulted in the compiler screaming Error signs at me.
> So how does one do it?

This requires heavy trickery, because what you're essentially doing is
taking a compile-time construct (type-safe variadic functions) and
applying it at runtime (array elements don't know how many arguments
they will have until actually initialized at runtime). The solution is
non-obvious, but, thankfully, *possible*, 'cos D is just *that* awesome.

An example of how to do this can be found in Adam Ruppe's eventloop.d
module, available here:


In particular, look at the `typehash` template, the addListener() and
send() functions, and the WrappedListener interface (along with the
wrap() function). That should give you the basic idea of what's
involved. Past that, there are also some dirty implementation details
you have to work with such as getPtrPair() that performs some
compiler-dependent type-casting black magic just to tie things together.

(Alternatively, you could just use eventloop.d in your game and save
yourself the trouble of reinventing it yourself. ;-)  It has a pretty
nice API that I've used in my own projects quite successfuly.)


Shin: (n.) A device for finding furniture in the dark.

Reply via email to