dimanche 26 août 2018

Inheritance and templates, a weird behaviour

I am trying to develop an event-based state machine for a couple hours now and I'm failing to identify why the templated classes bellow dont match. Basically, State publishes events and a StateMachine listens to them. Here goes a snippet:

#include <iostream>
#include <vector>

// Interface for event listening
template <typename Event, typename Sender>
class EventListener
{
public:
    virtual ~EventListener() = default;
    virtual void onEvent(const Sender* sender, const Event& data) = 0;
};

// Abstract class for event publishing
template <typename Event>
class EventPublisher
{
public:
    typedef EventListener<Event, EventPublisher> Listener;
    virtual ~EventPublisher() = default;

    // Queues an event listener
    void attach(Listener* listener) {
        listeners.push_back(listener);
    }

protected:
    // Publishes an event among all registered listeners
    void publish(const Event& e) {
        for (Listener* listener : listeners) {
            listener->onEvent(this, e);
        }
    }

private:
    std::vector<Listener*> listeners;
};

// Concrete publisher & listener
class StateEvent {};
class StateEventPublisher : public EventPublisher<StateEvent> {};
class StateEventListener : public EventListener<StateEvent, StateEventPublisher> {};

class State : public StateEventPublisher {
public:
    void foo() {
        publish(StateEvent());
    }
};

class StateMachine final : public StateEventListener {
private:
    void onEvent(const StateEventPublisher* sender, const StateEvent& e) override {}
};

int main()
{
    State state;
    StateMachine machine; // Is a StateEventListener, which is a EventListener<StateEvent, StateEventPublisher>, whereas StateEventPublisher is a EventPublisher<StateEvent>

    state.attach(&machine); // Incompatible with EventListener<StateEvent, EventPublisher<StateEvent>>*
    state.foo();

    return 0;
}

Why does the machine cant be attached to the state, if a machine is a StateEventListener, which is a EventListener<StateEvent, StateEventPublisher>, whereas a StateEventPublisher is a EventPublisher<StateEvent>?! What am I doing wrong?!

Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire