I’m making a Gui API for games. Basically I have event callbacks in my class which are function pointers. I thought of directly letting the user = the function pointer ex:
widget->OnPaintCallback = myPaintFunc;
But I don’t like how I cannot check for NULL or do anything else. It also makes my class feel exposed.
I also thought of having a setter for each callback, but that will get messy in the class (I have over 50)
I then thought of a function that asks for a string indicating which event the handler is for, and its function pointer. But that would evolve needlessly referencing documentation to know the string, and even more confusing for custom undocumented widgets.
Is there a better, cleaner alternative?
Thanks
Could casablankca’s solution have multiple arguments?
How about making the callback (
OnPaintCallback) an object of a class that overloadsoperator =, that way you can do any additional checking and throw an exception if something goes wrong. You can also overloadoperator ()so that you can call this object as if it were a simple function pointer.Update: As for variable number of function arguments, there is no general way to do it, but if your maximum N is limited and small, you could use template specializations, for example: (I’ve omitted constructors,
operator =and other details for clarity)I know this is a hacky way to do it but at least your users won’t see any of this: they’ll get the same interface for all callbacks.