I have a series of callbacks, that doing some job with input data and then call next callback in that series. Look at this simple example (each callback in series increment and print the value):
#include <stdio.h>
//#include <boost/bind.hpp>
//#include <boost/function.hpp>
//typedef boost::function<void (int i)> DataCallback;
typedef void (*DataCallback)(int i);
class A
{
public:
DataCallback dataCallback;
void RegisterCallback(DataCallback callback);
void Callback(int i);
};
void A::RegisterCallback(DataCallback callback)
{
dataCallback = callback;
}
void A::Callback(int i)
{
dataCallback(++i);
printf("Callback. i = %i", i);
}
int main (void)
{
A a1, a2, a3;
//a1.RegisterCallback(boost::bind(&A::Callback, &a2));
//a2.RegisterCallback(boost::bind(&A::Callback, &a3));
a1.RegisterCallback(a2.Callback);
a2.RegisterCallback(a3.Callback);
a3.Callback(1);
return 0;
}
But I have a problem. In C++, you cannot use class member function as callbacks. As I know, solution of this problem is making callback function static. But in this case, I can't use in-class fields. To solve it, I can provide to callback pointer to class (this) and use it in callback. But, in my case, it mean, that I should provide to the lowest callback (a3.Callback) pointers to a2 and a1.
In my real project, I have about 6 callbacks and provide to 6th callbacks pointers to other 5 - is a bad idea, i think.
So, my question is - how to implement this series of callbacks?
As you can see in code, I tried to use boost::function and boost::bind, but MSVS2005 crashes on compile-time (Optimized Compiler has stoped working...) with warning C4180 at mem_fn.hpp@318. What is wrong here and is this the optimal way to solve my problem?