Skip to content

Instantly share code, notes, and snippets.

@x4x
Last active October 21, 2016 08:55
Show Gist options
  • Save x4x/a70dde9ca317aa1d10f77d19f4223ff3 to your computer and use it in GitHub Desktop.
Save x4x/a70dde9ca317aa1d10f77d19f4223ff3 to your computer and use it in GitHub Desktop.
minimalistic list event handler in C++
/**
* minimalistic event handler
* @author x4x
* @version 0.2a
**/
#include <iostream>
using namespace std;
//#include <cstddef>
#include <stddef.h>
// event handler
class Handler
{
private:
// linkd list for event pointers
struct node {
void (*event)(void);
node *next;
};
node *root = NULL;
node *ptr = NULL;
// get last node.
node last() {
ptr = root;
if ( !ptr ) { //< exists a first element?
while( ptr->next ) { //< go to last element.
ptr = ptr->next;
}
return *ptr;
}
return *root;
}
public:
// append a event to be executed.
void append_event( void (*event)() ) {
if( !root ) { //< exists a root element
root = new node; //< create first element
ptr = root;
} else {
*ptr = last(); //< go to last element
ptr->next = new node; //< append new element
ptr = ptr->next; //< go to apendet element
}
ptr->next = NULL; //< set NULL ptr
ptr->event = event; //< set ptr to event
}
void trigger() {
ptr = root; //start with root
while( ptr ) {
(*ptr->event)(); //< execute element
ptr = ptr->next; //< goto next element
}
}
};
// Test:
void hallo() { //< test function
cout << "hallo" << endl;
}
int main() { //< tests
Handler handler;
//hallo();
handler.append_event( &hallo );
handler.append_event( &hallo );
handler.trigger();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment