Designing an EventHandler in C++
Been a while since I've done much in the way of heavy C++ &amp; I'm sure others will weigh in with their own suggestions, but my two cents:


I think the best solution is the first one you rejected: add Foo::{Add,Remove}Listener. Yep, it's more code but (a) it solves both the issues you observe with the code & (b) the implementation of these methods will be trivial. It's a compromise: better encapsulation in exchange for a little more code.

If you're really set on your approach, I'm pretty sure you could work around issue #1 by separating EventHandler into two classes (e.g. EventHandler & EventTrigger) & using friends to expose the dirty details, but IMO that's comparatively ugly. This stuff doesn't deserve that kind of hack.

Along that line of thinking but maybe a little cleaner: have EventTrigger derive from EventHandler (the former providing ::Trigger, the latter ::{Add,Remove}Listener), making m_handler an EventTrigger & having Foo::SomeHandler return a pointer to an EventListener -- effectively "hiding" the Trigger method from the outside world. You're still "leaking" here because you'll need to expose a protected instance variable or method (the list of listeners), but this stuff is simple enough that it shouldn't be completely abhorrent.


Depends what you consider a "flaw" :) Implementors of IDelegate might find the fact the method is const to be annoying (but then you might be making assumptions about implementations of IDelegate that I'm not aware of). Other than that & the issues you observed, things look fine to me.