Created
May 19, 2019 17:59
-
-
Save aprell/d17889cb764c5313b2dc6e582d9d5a29 to your computer and use it in GitHub Desktop.
Slightly different take on http://dunkels.com/adam/pt/expansion.html (2)
This file contains hidden or 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 <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