Events in C++

后端 未结 5 892
遇见更好的自我
遇见更好的自我 2021-01-31 10:32

I\'m not sure how to look for this online... I think they might be called something different in C++

I want to have a simple event system, somthing like

         


        
相关标签:
5条回答
  • 2021-01-31 10:42

    Take a look at the boost signal library. Combined with the function and bind libraries, you can do exactly what you are looking for.

    0 讨论(0)
  • 2021-01-31 10:46

    I use sigslot for exactly this purpose.

    0 讨论(0)
  • 2021-01-31 10:47

    The observer pattern from the GOF is pretty much what you want.

    In the book, it has C++ code for this...

    Also, as always, Boost has stuff you can make use of as well

    0 讨论(0)
  • 2021-01-31 10:48

    There is a native Visual C++ event system. It's mostly for COM, but it has native C++ support too.

    From here:

    [event_source(native)]
    class CSource {
    public:
       __event void MyEvent(int nValue);
    };
    
    [event_receiver(native)]
    class CReceiver {
    public:
       void MyHandler1(int nValue) {
          printf_s("MyHandler1 was called with value %d.\n", nValue);
       }
    
       void MyHandler2(int nValue) {
          printf_s("MyHandler2 was called with value %d.\n", nValue);
       }
    
       void hookEvent(CSource* pSource) {
          __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);
          __hook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);
       }
    
       void unhookEvent(CSource* pSource) {
          __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler1);
          __unhook(&CSource::MyEvent, pSource, &CReceiver::MyHandler2);
       }
    };
    
    int main() {
       CSource source;
       CReceiver receiver;
    
       receiver.hookEvent(&source);
       __raise source.MyEvent(123);
       receiver.unhookEvent(&source);
    }
    
    0 讨论(0)
  • 2021-01-31 10:51

    I use libsigc++. It's native for gtkmm.

    A simple example losely adapted from the tutorial:

    #include <iostream>
    #include <sigc++/sigc++.h>
    
    using namespace std;
    
    class AlienDetector {
    public:
            void run ();
            sigc::signal<void> signal_detected;
    };
    
    void warn_people () {
            cout << "There are aliens in the carpark!" << endl;
    }
    
    void AlienDetector::run () {
            signal_detected.emit ();
    }
    
    int main () {
            AlienDetector mydetector;
            mydetector.signal_detected.connect (sigc::ptr_fun (warn_people));
            mydetector.run ();
    }
    

    It also provides a mechanism to connect member-functions of specific objects to signals using sigc::mem_fun instead of sigc::ptr_fun:

    sigc::mem_fun (someobject, &SomeClass::some_method);
    

    This pretty much provides anything that is possible with GLib-signals.

    0 讨论(0)
提交回复
热议问题