Search code examples
c++c++11event-handlingstd-functionstdbind

C++ Callbacks for an Event Manager using std::function and std:bind with derived classes as parameters


I have the following Event Manager:

AppEventManager.h

#pragma once

#define GF_BIND_FN(fn) std::bind(&fn, this, std::placeholders::_1)

struct Event
{
public:
    enum EventType
    {
        AppQuit,
        AppBackground,

        WindowResize,
        WindowGainFocus,
        WindowLostFocus

    };

    EventType type = EventType::AppQuit;

    Event(EventType type) : type(type) {}
};

struct WindowResizedEvent : public Event
{
public:
    int width = 0;
    int height = 0;

    WindowResizedEvent(int width, int height) : width(width), height(height), Event(Event::EventType::WindowResize) {}
};

typedef std::function<void(Event&)> Callback;


class AppEventManager
{
public:

    static void AddListener(Event::EventType type, Callback c);

    template <typename T>
    static void TriggerEvent(Event& event);

private:

    static std::map<Event::EventType, std::vector<Callback>> listeners;
};


template<typename T>
inline void AppEventManager::TriggerEvent(Event& event)
{
    std::map<Event::EventType, std::vector<Callback>>::iterator it = listeners.find(event.type);

    if (it != listeners.end())
    {
        for (auto& callback : it->second)
        {
            callback(static_cast<T&>(event));
        }
    }
}

AppEventManager.cpp

#include "AppEventManager.h"

std::map<Event::EventType, std::vector<Callback>> AppEventManager::listeners = std::map<Event::EventType, std::vector<Callback>>();

// Store callback function for each event type
void AppEventManager::AddListener(Event::EventType type, Callback c)
{
    std::map<Event::EventType, std::vector<Callback>>::iterator it = listeners.find(type);

    if (it != listeners.end())
    {
        for (auto& callback : it->second)
        {
            // Check if callback exist
            if (callback.target_type().hash_code() == c.target_type().hash_code())
            {
                return;
            }
        }
    }

    listeners[type].emplace_back(c);
}

To add a listener:

Window::Window()
{
    AppEventManager::AddListener(Event::EventType::WindowResize, GF_BIND_FN(Window::WindowResized));
}

void Window::WindowResized(Event& event)
{
    if (event.type == Event::EventType::WindowResize)
    {
        WindowResizedEvent e = reinterpret_cast<WindowResizedEvent&>(event);
        windowWidth = e.width;
        windowHeight = e.height;
    }
}

To Trigger the Event:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    case WM_SIZE:
    {
        WindowResizedEvent event(LOWORD(lParam), HIWORD(lParam)); <---
        AppEventManager::TriggerEvent<WindowResizedEvent>(event); <---
    }
        break;
    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

This code works but as you see in void Window::WindowResized(Event& event) I need to cast the Event to the derived WindowResizedEvent.

What I want to achieve is to call void Window::WindowResized(Event& event) directly with the WindowResizedEvent parameter: void Window::WindowResized(WindowResizedEvent & event) but now it's not possible because typedef std::function<void(Event&)> Callback; requires the parameter to be Event and not derived from Event.

I couldn't find other ways to solve this and I don't know if is possible.

If you know a completely different way to achieve this it's also ok.


Solution

  • You could have separate vectors for each type. Access them through template functions.

    class AppEventManager
    {
    public:
    
        template <typename T>
        static void AddListener(std::function<void(T&)> callback) {
            get_listeners<T>().push_back(std::move(callback));
        }
    
        template <typename T>
        static void TriggerEvent(T& event) {
            for (auto& listener : get_listeners<T>()) {
                listener(event);
            }
        }
    
    private:
    
        template <typename T>
        static std::vector<std::function<void(T&)>>& get_listeners() {
            static std::vector<std::function<void(T&)>> listeners;
            return listeners;
        }
    };
    

    And used with the type directly instead of an enum.

    Window::Window()
    {
        AppEventManager::AddListener<WindowResizedEvent>(GF_BIND_FN(Window::WindowResized));
    }
    

    As a side note it's recommended to use lambdas instead of std::bind.

    Window::Window()
    {
        AppEventManager::AddListener<WindowResizedEvent>([&](WindowResizedEvent& event) { WindowResized(event); });
    }