我尝试了解新协程在 C++20 中的具体工作原理,但除了非常琐碎的示例之外,我无法使其工作。
我的目标是创建深层嵌套函数,允许最内部的函数可以中断并将控制权返回给最外部的代码,并且在某些条件后它将控制权返回给该内部函数。这是有效的setjmp并且longjmp。
我使用网络中找到的一些示例搞砸了一些代码:
#include <iostream>
#include <coroutine>
#include <optional>
template <typename T>
struct task
{
struct task_promise;
using promise_type = task_promise;
using handle_type = std::coroutine_handle<promise_type>;
mutable handle_type m_handle;
task(handle_type handle)
: m_handle(handle)
{
}
task(task&& other) noexcept
: m_handle(other.m_handle)
{
other.m_handle = nullptr;
}
bool await_ready()
{
return m_handle.done();
}
bool await_suspend(std::coroutine_handle<> handle)
{
if (!m_handle.done()) {
m_handle.resume();
}
return !m_handle.done();
}
auto await_resume()
{
return result();
}
T result() const
{
if (!m_handle.done()) …Run Code Online (Sandbox Code Playgroud)