I have Consequence, Event and EventsConsequences classes.
Each Event's derived class has the list of Consequence objects that it triggers stored in EventsConsequences object. If two Event objects are of the same type (class) then they must trigger the same Consequences.
So in EventsConsequences class I have:
unordered_map<std::type_index, std::vector<Consequence*>> consequences;
template<typename Event>
void add_trigger_of(Consequence *consequence) {
consequences[typeid(Event)].push_back(consequence);
}
template<typename Event>
void trigger_consequences_of(Event *event) {
for (Consequence *consequence : consequences[typeid(Event)]);
consequence->react_to(event);
}
In Event class:
EventsConsequences* consequences;
void trigger() {
consequences->trigger_consequences_of(this);
}
And, of course, I have many derived classes of both Event and Consequence.
What I want is for it to work, but it doesn't. It always calls
EventsConsequences::trigger_consequences_of<Event>(Event*)
But not of a derived classes.
The only idea I have to fix this is to make Event::trigger() virtual and for every derived class override it
void DerivedEvent::trigger() override {
consequences->trigger_consequences_of(this);
}
But I hate writing WET code. Are there any other ways of doing it?
typeid()then it's usually an indication that your design could use a rethink. I don't immediately have a replacement to suggest, though.