Skip to content

Instantly share code, notes, and snippets.

@abdalmoez
Created April 20, 2020 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdalmoez/b9c298f21d37c277747c1e6b8c447118 to your computer and use it in GitHub Desktop.
Save abdalmoez/b9c298f21d37c277747c1e6b8c447118 to your computer and use it in GitHub Desktop.
Creating Event call back for all instance of a class
#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