Skip to content

Instantly share code, notes, and snippets.

@Ation
Last active August 29, 2015 14:06
Show Gist options
  • Save Ation/d6091472b811aa2a7736 to your computer and use it in GitHub Desktop.
Save Ation/d6091472b811aa2a7736 to your computer and use it in GitHub Desktop.
Chain
#include <functional>
#include <deque>
#include <stdexcept>
template<class T = void*> class Chain {
public:
typedef Chain<T> my_type;
typedef std::function< T (my_type &) > callback;
typedef std::function< void (my_type &, std::exception &) > fail_callback;
public:
Chain() : Chain( [] (my_type&, std::exception &) {} ) {}
explicit Chain( fail_callback &fcb) : m_fcb( fcb ) {}
Chain& then( callback &cb) {
m_chain.emplace_back( cb );
return *this;
}
void done(T &val) {
m_val = val;
if ( !m_chain.empty() ) {
try {
auto cb = m_chain.front();
m_chain.pop_front();
cb(*this);
} catch ( std::exception &err) {
cancel(err);
} catch (...) {
clear_queue();
}
}
}
T& value() const {
return this->val;
}
private:
void cancel(std::exception &err) {
failcb( *this, err );
clear_queue();
}
void clear_queue() {
m_chain.clear();
}
T m_val;
std::deque<callback> m_chain;
fail_callback m_fcb;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment