Created
November 24, 2011 12:38
-
-
Save deoxxa/1391265 to your computer and use it in GitHub Desktop.
Asynchronous callbacks..? Kind of?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <deque> | |
#include <boost/function.hpp> | |
template <typename ...Args> | |
class CallbackQueue | |
{ | |
public: | |
typedef boost::function< bool (CallbackQueue< Args... >&, Args...) > callback_t; | |
typedef std::deque< callback_t > callbackList_t; | |
private: | |
callbackList_t m_callbackList; | |
typename callbackList_t::iterator m_step; | |
public: | |
CallbackQueue(callback_t whenDone) | |
{ | |
m_callbackList.push_back(whenDone); | |
} | |
void addCallback(callback_t callback) | |
{ | |
m_callbackList.insert((m_callbackList.end())-1, callback); | |
} | |
void run(Args... args) | |
{ | |
m_step = m_callbackList.begin(); | |
doNextStep(args...); | |
} | |
void doNextStep(Args... args) | |
{ | |
(*m_step++)(*this, args...); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/bind.hpp> | |
#include "callbackqueue.h" | |
typedef CallbackQueue<int*,int*> myCallbacks_t; | |
// Imagine these are asynchronous, please! | |
bool cbA(myCallbacks_t q, int* a, int* b) { ++(*a); q.doNextStep(a, b); return true; } | |
bool cbB(myCallbacks_t q, int* a, int* b) { ++(*b); q.doNextStep(a, b); return true; } | |
bool whenDone(myCallbacks_t q, int* a, int* b) { std::cout << *a << "," << *b << std::endl; return true; } | |
int main(int argc, char** argv) | |
{ | |
myCallbacks_t queue(boost::bind(whenDone, _1, _2, _3)); | |
queue.addCallback(boost::bind(cbA, _1, _2, _3)); | |
queue.addCallback(boost::bind(cbB, _1, _2, _3)); | |
int a = 0, b = 0; | |
queue.run(&a, &b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment