簡體   English   中英

使用 std::function 和 std:bind 以及派生類作為參數的事件管理器的 C++ 回調

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

我有以下事件管理器:

應用事件管理器.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));
        }
    }
}

應用事件管理器.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);
}

添加監聽器:

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;
    }
}

觸發事件:

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;
}

此代碼有效,但正如您在void Window::WindowResized(Event& event)看到的那樣,我需要將事件轉換為派生的 WindowResizedEvent。

我想要實現的是直接使用 WindowResizedEvent 參數調用void Window::WindowResized(Event& event)void Window::WindowResized(WindowResizedEvent & event)但現在這是不可能的,因為typedef std::function<void(Event&)> Callback; 要求參數為 Event 而不是從 Event 派生的。

我找不到其他方法來解決這個問題,我不知道是否可能。

如果您知道一種完全不同的方法來實現這一點,那也沒關系。

您可以為每種類型設置單獨的向量。 通過模板函數訪問它們。

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;
    }
};

並直接與類型一起使用,而不是與枚舉一起使用。

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

作為旁注,建議使用 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