Skip to content

Instantly share code, notes, and snippets.

@aprell
Created May 19, 2019 17:59
Show Gist options
  • Select an option

  • Save aprell/d17889cb764c5313b2dc6e582d9d5a29 to your computer and use it in GitHub Desktop.

Select an option

Save aprell/d17889cb764c5313b2dc6e582d9d5a29 to your computer and use it in GitHub Desktop.
Slightly different take on http://dunkels.com/adam/pt/expansion.html (2)
#include <functional>
#include <iostream>
template<typename T>
struct coro {
using fn = std::function<T(T)>;
coro(fn f) : m_lc(0), m_done(false), m_fn(f) {}
bool done() const { return m_done; }
T resume(T arg) { return m_fn(arg); }
unsigned int m_lc;
bool m_done;
private:
fn m_fn;
};
#define CORO_BEGIN(co) \
switch (co.m_lc) { case 0:
#define CORO_END(co, res) \
} co.m_lc = 0; co.m_done = true; return res
#define CORO_YIELD(co, res) \
co.m_lc = __LINE__; return res; case __LINE__:
int main()
{
coro<int> co([&](int n) {
static int i;
CORO_BEGIN(co);
for (i = 0; i < 5; i++) {
CORO_YIELD(co, n + i);
}
CORO_END(co, n + 5);
});
int n = 100;
while (!co.done()) {
n = co.resume(n);
std::cout << "Back in main with n = " << n << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment