Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8714763
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T05:40:42+00:00 2026-06-13T05:40:42+00:00

My Event Manager For a event manager I need to store many pointers to

  • 0

My Event Manager

For a event manager I need to store many pointers to functions in a vector to call them when the event is triggered. (I will provide the source code of the EventFunction helper class at the end of this question.)

// an event is defined by a string name and a number
typedef pair<string, int> EventKey;

// EventFunction holds a pointer to a listener function with or without data parameter
typedef unordered_map<EventKey, vector<EventFunction>> ListEvent;

// stores all events and their listeners
ListEvent List;

Registering an listener could be done by calling the first or the second function, depending on if you want receive additional data or not. (This code is from my event manager class.)

public:
  typedef void (*EventFunctionPointer)();
  typedef void (*EventFunctionPointerData)(void* Data);

  // let components register for events by functions with or without data parameter,
  // internally simple create a EventFunction object and call the private function
  void ManagerEvent::Listen(EventFunctionPointer Function, string Name, int State);
  void ManagerEvent::Listen(EventFunctionPointerData Function, string Name, int State);

private:
  void ManagerEvent::Listen(EventFunction Function, string Name, int State)
  {
    EventKey Key(Name, State);
    List[Key].push_back(Function);
  }  

Member Function Pointers

That code doesn’t work because I store function pointers but not member function pointers in my List. All these pointers should be member function pointers because a component like ComponentSound will listen to the event "PlayerLevelup" with on of its member functions ComponentSound::PlayerLevelup to play a nice sound if the event is triggered.

A member function pointer in C++ looks like this.

// ReturnType (Class::*MemberFunction)(Parameters);
void (ComponentSound::*PlayerLevelup)();

The problem is, any component class should be able to listen for events, but storing the member function pointers in the event manager requires me to specify the listening class. As you can see in the example, I need to specify ComponentSound but the event manager should simply have a vector of member function pointers to any class.

Question

An Answer to one of these question would help me a lot.

  • How can I store function pointers to any member function in a vector in my event manager? (Maybe it helps that all the listening functions are inherited from one abstract class Component.)
  • How can I design my event manager in another way to reach the aimed functionality? (I want to use string and int keys for messages.)

I tried to keep my question general but if you need more informations or code please comment.

Assignments

In my vector of member function pointers I use EventFunction instead of only a pointer to provide two message types. One with, and one without a data parameter.

class EventFunction
{
private: EventFunctionPointer Pointer; EventFunctionPointerData PointerData; bool Data;
public:
    EventFunction(EventFunctionPointer Pointer) : Pointer(Pointer), PointerData(NULL), Data(false) { }
    EventFunction(EventFunctionPointerData PointerData) : PointerData(PointerData), Pointer(NULL), Data(true) { }
    EventFunctionPointer GetFunction() { return Pointer; }
    EventFunctionPointerData GetFunctionData() { return PointerData; } bool IsData() { return Data; }
    void Call(void* Data = NULL){ if(this->Data) PointerData(Data); else Pointer(); }
};
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T05:40:43+00:00Added an answer on June 13, 2026 at 5:40 am

    Not a direct response, so bear with me.

    Before we start: This is generally referred to as the Observer pattern, you might find lots of confused information on the web about it, and many failed implementations, but who knows you might also strike gold.

    Okay, so first the question has a fundamental flaw: it fails to consider that capturing object references is tricky, because object lifetimes are bounded.

    Therefore, even before we delve into the specifics of an implementation we need to ask ourselves how to handle stale references. There are two basic strategies:

    1. Not having stale references, this implies that registered objects unregister themselves automatically upon destruction. The mechanism can be factored out in a base class.

    2. Having a way to tell good and stale references apart when inspecting them, and lazily collecting the stale ones. The mechanism can be enforced using a shared_ptr/weak_ptr pair and realizing that weak_ptr are observers of the shared_ptr.

    Both solutions are viable and neither implementation is perfect. The base class mechanism assumes you can actually modify your class hierarchy while the weak_ptr trick assumes that all observes will be heap-allocated and their lifetime controlled by a weak_ptr.

    I will make an example using shared_ptr (and make use of a number of C++11 facilities, though none is mandatory here):

    class EventManager {
        typedef std::unique_ptr<Observer> OPtr;
        typedef std::vector<OPtr> Observers;
    public:
    
        // Callback observers of "name"
        // Returns the number of observers so invoked
        size_t signal(std::string const& name) const {
            auto const it = _observers.find(name);
            if (it == _observers.end()) { return 0; }
    
            Observers& obs = it->second;
    
            size_t count = 0;
            auto invoker = [&count](OPtr const& p) -> bool {
                bool const invoked = p->invoke();
                count += invoked;
                return not invoked; // if not invoked, remove it!
            };
    
            obs.erase(std::remove_if(obs.begin(), obs.end(), invoker), obs.end());
    
            if (obs.empty()) { _observers.erase(it); }
    
            return count;
        }
    
        // Registers a function callback on event "name"
        void register(std::string const& name, void (*f)()) {
            _observers[name].push_back(OPtr(new ObserverFunc(f)));
        }
    
        // Registers an object callback on event "name"
        template <typename T>
        void register(std::string const& name, std::shared_ptr<T> const& p, void (T::*f)()) {
            _observers[name].push_back(OPtr(new ObserverMember<T>(p, f)));
        }
    
    
    private:
        struct Observer { virtual ~Observer() {} virtual bool invoke() = 0; };
    
        struct ObserverFunc: Observer {
            ObserverFunc(void (*f)()): _f(f) {}
    
            virtual bool invoke() override { _f(); return true; }
    
            void (*_f)();
        };
    
        template <typename T>
        struct ObserverMember: Observer {
            ObserverT(std::weak_ptr<T> p, void (T::*f)()): _p(p), _f(f) {}
    
            virtual bool invoke() override {
                std::shared_ptr<T> p = _p.lock();
                if (not p) { return false; }
    
                p->*_f();
                return true;
            }
    
            std::weak_ptr<T> _p;
            void (T::*_f)();
        };
    
        // mutable because we remove observers lazily
        mutable std::unordered_map<std::string, Observers> _observers;
    }; // class EventManager
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have event manager process that dispatches events to subscribers (e.g. http_session_created, http_sesssion_destroyed). If
assumption: Event\Service\EventService is my personal object that works with Event\Entity\Event entities This code works
I am working on an event manager where events are represented by a key
I have two blocks of validation code that I need to execute in a
I'm designing a UI manager class that will manage all my UI elements (this
I'm trying to figure out how to manage my event ids. Up to this
I developed a custom file manager for tinymce. But even if adding image to
Event-delegation must be used to make events work after inserting DOM elements (i.e Ajax
Why event.which doesn't return 13 (CR) or 10 (LF) depending on the operating system?
Some event handlers for the WinForm DataGridView have DataGridViewCellEventArgs as a parameter and a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.