Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typesafe callback system in modern C++

I'm working at a module that use a callback system that wasn't implemented very nice. The clients are registering with an ID and will be called back with a variable (or two, or none). The problem is that for almost every ID is a different variable. (Ex: Id1 -> char*, Id2 -> int). This is achieved by passing variable via a pointer. So callback looks like

typedef void (*NotifFunctionPtr)(void* ctx, const void* option);

There are many problems with this approach like, and I want to replace this with a (type) safe and modern way of handling this. However this isn't as simple as it looks like, I have some ideas (like boost::function or replacing the void* with a struct that encapsulate type and ptr) but i think maybe there is a better idea, so I was wondering what is the modern way of settings a typesafe callback in C++.

Edit: Another idea is registering an callback with a type T via a template function that calls back with the same type T. Is this viable or implemented in a library somewere ?

like image 775
cprogrammer Avatar asked Dec 06 '22 18:12

cprogrammer


1 Answers

Your problem is not that of callbacks, but rather that you want to treat all callbacks as the same type, when they are not (the signatures are different). So either you do the nasty C void* trick or if you want to use a type-safe approach you will have to pay for it, and provide different methods to register the different callback types --which IMHO is the right way.

Once you have solved that, you can use the signals or signals2 libraries or else implement your own wheel using function as a base (to avoid having to rewrite the type erasure).

like image 187
David Rodríguez - dribeas Avatar answered Dec 29 '22 08:12

David Rodríguez - dribeas