After my initial research I found that std::function could handle most of this for me and is also part of the C++ standard (thus the std namespace). Unfortunately it must have been a new addition to the standard since it didn't seem to exist on my older version of g++ (not even in the tr1 namespace). Since I tend to only use features that are in the lowest common denominator of platforms (and because I like to hack on code ;), I decided to write my own simple alternative.
Function pointers in C++ are seemingly
more complex than their C counterparts because the class instance
needs to be known in order for the callback to work. I decided to get
around this issue by introducing templates so the type of the
“callback class” could easily be specified. When working with
templates, it quickly began getting messy since the template type had
to keep being specified every time the function pointer class was
being passed around in the application logic. So to get around this I
inherited from a more generic Function class. This can be seen in the
So now a GUI component such as a button can contain a fully encapsulated function pointer for it's onClickEvent(). This can also be put inside an auto_ptr container to prevent any memory leaks. The only real work now is making sure that the class containing the method that the function points to is not deleted when being called but if the software has correct logic, this will be very unlikely anyway.
In short, I no longer need be jealous of the callback systems found in javax.swing or Windows.Forms since although done quite differently, my GUI library should hopefully be as straightforward to use in this respect.
From the code above it is also trivial to add a template class similar to GenericFunction which can take a void* parameter so the caller (i.e Button) can also be passed when calling the function pointer's function, so it is possible for the programmer to determine in code, which button triggered the callback.