| 1 |
// { dg-do run } |
| 2 |
// { dg-skip-if "requires hosted libstdc++ for cstdlib abort" { ! hostedlib } } |
| 3 |
|
| 4 |
#if __has_include(<coroutine>) |
| 5 |
#include <coroutine> |
| 6 |
#else |
| 7 |
#include <experimental/coroutine> |
| 8 |
namespace std { |
| 9 |
using namespace std::experimental; |
| 10 |
} |
| 11 |
#endif |
| 12 |
#include <cstdlib> |
| 13 |
|
| 14 |
template <typename T> |
| 15 |
struct generator{ |
| 16 |
struct promise_type; |
| 17 |
using coro_handle = std::coroutine_handle<promise_type>; |
| 18 |
|
| 19 |
struct promise_type{ |
| 20 |
std::suspend_always yield_value (T value){ |
| 21 |
value_ = value; |
| 22 |
return {}; |
| 23 |
} |
| 24 |
std::suspend_always initial_suspend (){ |
| 25 |
return {}; |
| 26 |
} |
| 27 |
std::suspend_always final_suspend () noexcept { |
| 28 |
return {}; |
| 29 |
} |
| 30 |
|
| 31 |
std::suspend_never return_void() |
| 32 |
{ |
| 33 |
return {}; |
| 34 |
} |
| 35 |
generator get_return_object () { |
| 36 |
return {coro_handle::from_promise(*this)}; |
| 37 |
} |
| 38 |
void unhandled_exception () { |
| 39 |
return; |
| 40 |
} |
| 41 |
T value_; |
| 42 |
}; |
| 43 |
coro_handle handle; |
| 44 |
generator(coro_handle h) |
| 45 |
:handle(h) |
| 46 |
{} |
| 47 |
~generator(){ |
| 48 |
if(handle) |
| 49 |
handle.destroy(); |
| 50 |
} |
| 51 |
|
| 52 |
bool resume(){ |
| 53 |
if(not handle.done()) |
| 54 |
handle.resume(); |
| 55 |
return not handle.done(); |
| 56 |
}; |
| 57 |
|
| 58 |
T get () { |
| 59 |
return handle.promise().value_; |
| 60 |
} |
| 61 |
}; |
| 62 |
namespace A |
| 63 |
{ |
| 64 |
} |
| 65 |
|
| 66 |
generator<int> |
| 67 |
parse() |
| 68 |
{ |
| 69 |
namespace B = A; |
| 70 |
co_yield 1; |
| 71 |
} |
| 72 |
|
| 73 |
int main() |
| 74 |
{ |
| 75 |
auto gen = parse(); |
| 76 |
gen.handle.resume (); /* init suspend. */ |
| 77 |
if (gen.get() != 1) |
| 78 |
abort (); |
| 79 |
return 0; |
| 80 |
} |