I'm writing some code that includes events which are custom-implemented and class that uses these events and invokes them when something happens(ex. window closes). It looks something like this:
// phony.h
class Phony
{
public:
Phony();
~Phony();
// some stuff
void i_invoke_click();
void i_invoke_resize();
private:
Event<Arg1> click;
Event<> resize;
Event<Arg2> event3;
Event<Arg3> event4;
};
// event.h
template <typename... Args>
class Event
{
public:
void invoke(Args... params) const
void add(std::function<void(Args...)> func)
void remove(std::function<void(Args...)> func)
void operator+=(std::function<void(Args...)> func) // same as add
void operator-=(std::function<void(Args...)> func) // same as remove
void operator()(Args... params) // invoke
private:
std::list<std::function<void(Args...)>> invoke_list;
};
Now I need to implement some interface so other classes could subscribe/unsubscribe to events like click. I have considered two ways to do this:
- Make access methods like
subscribe_to_click(func)(which will make many methods and not convenient) - Or make events public so you could directly access them via +=(which is convenient)
But I think that second way of putting events violates encapsulation but I'm not sure in it. So the question is: Is it okay to leave events public or I should make it the ugly(but safe) way?