0

I've got the following code for my event manager:

#pragma once

namespace EventManager {
    enum class EventType {
        OnUpdate,
        OnDraw,
        Size
    };
    extern std::vector<void*> EventCallbacks[(unsigned int)EventType::Size];

    void AddEventHandler(EventType eventId, void* callback);
    void RemoveEventHandler(EventType eventId, void* callback);

    template <typename... Args>
    void Trigger(EventType eventId, Args... args) {
        for (auto callback : EventCallbacks[(unsigned int)eventId]) {
            static_cast<void(*)(Args...)>(callback)(args...);
        }
    }

    template <typename... Args>
    bool TriggerProcess(EventType eventId, Args... args) {
        auto process = true;
        for (auto callback : EventCallbacks[(unsigned int)eventId]) {
            if (!static_cast<bool(*)(Args...)>(callback)(args...)) {
                process = false;
            }
        }
        return process;
    }
}

And I'm trying to call EventManager::AddEventHandler from inside another class, but I'm getting the following error:

Error

It works fine if I try to do that from a namespace instead of class, but I can't seem to figure out how to make it work from inside this class.

P Sawicki
  • 189
  • 1
  • 2
  • 9
  • Note that a member function has an implicit first argument which is a pointer to the class it belongs to. If you want `OnUpdate` or `OnDraw` to mutate the original object, you need to store those in a functor or something. – JohnFilleau Nov 09 '21 at 19:10
  • I tried that before, didn't work https://i.imgur.com/SAkknXR.png – P Sawicki Nov 09 '21 at 19:13
  • You also need to be careful when passing around member functions paired with their `this` pointer. If you copy or move the object, then you may invalidate the `this` pointer. – JohnFilleau Nov 09 '21 at 19:13
  • Are you sure a member function is allowed here? You can always do a `reinterpret_cast`, but a free function if a free function is expected, this would be problematic: https://stackoverflow.com/questions/12662891/how-can-i-pass-a-member-function-where-a-free-function-is-expected But why on earth did you make `EventManager` a namespace instead of a class. It pretty much sounds like a entity and using a namespace instead of a class you limit reusability... – fabian Nov 09 '21 at 19:14
  • 1
    First, your AddEventHandler accepts `void *`, which should be `void (*callback)()`. Second, make your OnUpdate/OnDraw functions static. – ABacker Nov 09 '21 at 19:21
  • @ABacker Thank you, that seems to have solved the issue. – P Sawicki Nov 09 '21 at 19:26

0 Answers0