Callback functions in C++

Note: Most of the answers cover function pointers which is one possibility to achieve “callback” logic in C++, but as of today not the most favourable one I think. What are callbacks(?) and why to use them(!) A callback is a callable (see further down) accepted by a class or function, used to customize the … Read more

C++ lambda with captures as a function pointer

I just ran into this problem. The code compiles fine without lambda captures, but there is a type conversion error with lambda capture. Solution with C++11 is to use std::function (edit: another solution that doesn’t require modifying the function signature is shown after this example). You can also use boost::function (which actually runs significantly faster). … Read more

How can I pass a member function where a free function is expected?

There isn’t anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus void (aClass::*)(int, int) rather than the type … Read more

How can I pass a class member function as a callback?

This is a simple question but the answer is surprisingly complex. The short answer is you can do what you’re trying to do with std::bind1st or boost::bind. The longer answer is below. The compiler is correct to suggest you use &CLoggersInfra::RedundencyManagerCallBack. First, if RedundencyManagerCallBack is a member function, the function itself doesn’t belong to any … Read more

Using generic std::function objects with member functions in one class

A non-static member function must be called with an object. That is, it always implicitly passes “this” pointer as its argument. Because your std::function signature specifies that your function doesn’t take any arguments (<void(void)>), you must bind the first (and the only) argument. std::function<void(void)> f = std::bind(&Foo::doSomething, this); If you want to bind a function … Read more