Type callback system in modern C ++

I am working on a module that uses a callback system that has not been implemented very nicely. Clients are registered with an identifier and will be called back with a variable (either two or none). The problem is that almost every identifier uses a different variable. (Example: Id1 β†’ char* , Id2 β†’ int ). This is achieved by passing the variable through a pointer. So the callback looks like

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

There are many problems with this approach, and I want to replace this with a safe and modern way of handling this. However, it's not as simple as it seems, I have some ideas ( like boost::function or replacing void* with a structure that encapsulates type and ptr), but I think maybe there is a better idea, so I was wondering strong> what is the modern way to configure callback type in C ++.

Edit: Another idea is to register a callback with type T through a template function that accesses the same type of T. Is it viable or implemented in the library?

+4
source share
3 answers

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

After you solve this, you can use the signals or signals2 or implement your own wheel using function as a base (so as not to overwrite type erasure).

+10
source

boost::function is just the right choice. You get the security type of function objects without changing the code much.

+3
source

If you have already looked at boost. Why not use the signals or signals2 library.

+2
source

All Articles