Skip to content

Instantly share code, notes, and snippets.

@xentec
Created May 14, 2016 22:01
Show Gist options
  • Save xentec/e2dcf497c5840c24aa08da33ba2af42e to your computer and use it in GitHub Desktop.
Save xentec/e2dcf497c5840c24aa08da33ba2af42e to your computer and use it in GitHub Desktop.
#include <functional>
#include <stack>
struct Scope
{
using Callback = std::function<void()>;
Scope() = default;
Scope(Callback cb)
{
cbs.push(cb);
}
~Scope()
{
while(!cbs.empty())
{
// call all callbacks starting with the last
cbs.top()();
cbs.pop();
}
}
Scope& operator += (Callback cb)
{
cbs.push(cb);
return *this;
}
Callback operator --()
{
Callback cb = cbs.top();
cbs.pop();
return cb;
}
Scope operator -- (int)
{
Scope prev = *this;
cbs.pop();
return prev;
}
private:
std::stack<Callback> cbs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment