Instance based Callbacks in C++

One of the things that was probably forgotten but the dudes who made C++ standard were callbacks, there’s no out of the box solution for Instance based Callbacks, just for functions.
When I moved to C# I was really happy with the way delegates work, it’s simple, easy and most of all, it works.

On game development one of the things callbacks are usually used is for Buttons, you have a menu and want to attribute a function to each button. Sure you can point it to the same one and make a bunch of if’s and then point to a Global var which does the correct action, but this is not elegant and sure as hell not easy to add/modify stuff.

I came across a couple of solutions for having an instance based callback:
1- Do your own – I’ve made one that worked but couldn’t get around to add parameters. I think we might skip this one since you are probably looking for a quick solution.
2 – Use boost – If you don’t know this have a look, even for other stuff, Boost has tons of awesome apis for helping C++ development. Including smart pointers that basically delete themselves automatically.
3 – Use PlusCallback – I decided to use this one.

And it’s simple to use

// Callback without parameters
// My example class
Sprite* sprite = new Sprite();
cb::Callback0<void> call1;
// Bind callback
call1.Reset(sprite, &Sprite::SomeFunction);
// Call callback
// Example with parameter
cb::Callback1<void, Sprite*> call2; 
// Bind callback
call2.Reset(sprite, &Sprite::SomeFunctionWithParameterSprite);
// Your function should be something like 
// Sprite::SomeFunctionWithParameterSprite(Sprite* sprite);

Easy right? It even work with return, just switch that void to something else. Let me know if you find a better solution. For now I’m sticking with this one.

One Comment

  1. Sam Crew

    I think you’re reading the graph upside down. The Y axis is in iterations per second; a higher bar is faster. So native C++ callbacks are the fastest, and PlusCallback is slightly faster than Boost.

    I’ve tried PlusCallback, and IMO it’s by far the easiest to use and manage.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.