Last active
August 2, 2017 08:03
-
-
Save makomweb/6949866 to your computer and use it in GitHub Desktop.
Playing around with C++ events. Very similar to Qt's signal/slot mechanism.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
using namespace std; | |
[event_source(native)] | |
class Sender | |
{ | |
public: | |
__event void SendEvent(int value); | |
}; | |
[event_receiver(native)] | |
class Receiver | |
{ | |
string name_; | |
public: | |
Receiver(const string& name) : name_(name) {} | |
void OnEventReceived(int value) | |
{ | |
cout << name_.c_str() << " has received " << value << endl; | |
} | |
void hookEvents(Sender* pSender) | |
{ | |
__hook(&Sender::SendEvent, pSender, &Receiver::OnEventReceived); | |
} | |
void unhookEvents(Sender* pSender) | |
{ | |
__unhook(&Sender::SendEvent, pSender, &Receiver::OnEventReceived); | |
} | |
}; | |
int main() | |
{ | |
Sender sender; | |
Receiver receiver_1("one"); | |
receiver_1.hookEvents(&sender); | |
Receiver receiver_2("two"); | |
receiver_2.hookEvents(&sender); | |
sender.SendEvent(42); | |
receiver_1.unhookEvents(&sender); | |
sender.SendEvent(43); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment