Created
April 20, 2020 11:03
-
-
Save abdalmoez/b9c298f21d37c277747c1e6b8c447118 to your computer and use it in GitHub Desktop.
Creating Event call back for all instance of a class
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 <unordered_set> | |
class TestEvent { | |
private: | |
static std::unordered_set<TestEvent*> objects; | |
std::string m_title; | |
public: | |
TestEvent(const std::string& title):m_title (title) | |
{ | |
objects.insert(this); | |
} | |
~TestEvent() | |
{ | |
objects.erase(this) ; | |
} | |
template< typename FN > static void ApplyOnAllInstances( FN function_call_back ) | |
{ | |
for( TestEvent* obj : objects ) | |
{ | |
function_call_back(obj) ; | |
} | |
} | |
void onConnect() | |
{ | |
std::cout<<"Connecting '"<<m_title<<"'"<<std::endl; | |
} | |
void onDisconnect() | |
{ | |
std::cout<<"Disconnecting '"<<m_title<<"'"<<std::endl; | |
} | |
}; | |
std::unordered_set<TestEvent*> TestEvent::objects; | |
int main() | |
{ | |
TestEvent* t1 = new TestEvent("Instance 1"); | |
TestEvent* t2 = new TestEvent("Instance 2"); | |
TestEvent* t3 = new TestEvent("Instance 3"); | |
delete t3; | |
TestEvent::ApplyOnAllInstances([](TestEvent* t){t->onConnect();}); | |
TestEvent::ApplyOnAllInstances([](TestEvent* t){t->onDisconnect();}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment