tinycodinglm / cpp /cpp-coroutines-async.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.55 kB
{"type": "session", "harness": "opencode", "id": "cpp-coroutines-async", "name": "Use C++20 coroutines for async/await patterns and generators"}
{"type": "message", "message": {"role": "system", "content": "You are an expert C++ developer. You write clean, efficient, and idiomatic code."}}
{"type": "message", "message": {"role": "user", "content": "Use C++20 coroutines for async/await patterns and generators"}}
{"type": "message", "message": {"role": "assistant", "content": "#include <coroutine>\n#include <iostream>\n#include <vector>\n#include <optional>\n\ntemplate<typename T>\nstruct Task {\n struct promise_type {\n T value;\n Task get_return_object() { return Task{std::coroutine_handle<promise_type>::from_promise(*this)}; }\n std::suspend_never initial_suspend() { return {}; }\n std::suspend_never final_suspend() noexcept { return {}; }\n void return_value(T v) { value = v; }\n void unhandled_exception() { std::terminate(); }\n };\n\n std::coroutine_handle<promise_type> handle;\n T result() { return handle.promise().value; }\n ~Task() { if (handle) handle.destroy(); }\n};\n\n// Generator\ntemplate<typename T>\nstruct Generator {\n struct promise_type {\n T current;\n Generator get_return_object() { return Generator{std::coroutine_handle<promise_type>::from_promise(*this)}; }\n std::suspend_always initial_suspend() { return {}; }\n std::suspend_always final_suspend() noexcept { return {}; }\n std::suspend_always yield_value(T value) { current = value; return {}; }\n void unhandled_exception() { std::terminate(); }\n };\n\n std::coroutine_handle<promise_type> handle;\n bool next() { handle.resume(); return !handle.done(); }\n T value() { return handle.promise().current; }\n ~Generator() { if (handle) handle.destroy(); }\n};\n\nGenerator<int> fibonacci() {\n int a = 0, b = 1;\n while (true) {\n co_yield a;\n auto temp = a + b;\n a = b;\n b = temp;\n }\n}\n\nGenerator<int> range(int start, int end) {\n for (int i = start; i < end; ++i) co_yield i;\n}\n\nTask<int> compute(int x) {\n co_return x * x;\n}\n\nint main() {\n // Generator\n auto fib = fibonacci();\n for (int i = 0; i < 10; ++i) {\n fib.next();\n std::cout << fib.value() << \" \";\n }\n std::cout << \"\\n\";\n\n // Range\n auto r = range(0, 5);\n while (r.next()) std::cout << r.value() << \" \";\n std::cout << \"\\n\";\n\n return 0;\n}"}}