简体   繁体   English

使用 std::function 和 std:bind 以及派生类作为参数的事件管理器的 C++ 回调

[英]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应用事件管理器.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应用事件管理器.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.此代码有效,但正如您在void Window::WindowResized(Event& event)看到的那样,我需要将事件转换为派生的 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;我想要实现的是直接使用 WindowResizedEvent 参数调用void Window::WindowResized(Event& event)void Window::WindowResized(WindowResizedEvent & event)但现在这是不可能的,因为typedef std::function<void(Event&)> Callback; requires the parameter to be Event and not derived from Event.要求参数为 Event 而不是从 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.如果您知道一种完全不同的方法来实现这一点,那也没关系。

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 .作为旁注,建议使用 lambdas 而不是std::bind

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM