【发布时间】:2021-04-22 12:19:13
【问题描述】:
我决定编写自己的 awaitable 来让 loader 了解 C++ 协程是如何工作的。现在,我想构建自己的结构,相当于:
cppcoro::task<int> bar()
{
co_yield 42;
}
这是我在阅读CppReference's coroutine page 后想到的。其中状态 最后,调用了 awaiter.await_resume(),其结果是整个 co_await expr 表达式的结果。我假设更改 await_resume() 的返回类型足以同时给出 @987654325 @ 和 make_awaitable 功能相同。
#include <iostream>
#include <coroutine>
#include <cppcoro/task.hpp>
#include <cppcoro/sync_wait.hpp>
auto make_awaitable() {
using return_type = int;
struct awaitable {
bool await_ready() {return false;}
void await_suspend(std::coroutine_handle<> h) {
std::cout << "In await_suspend()" << std::endl;
h.resume();
}
int await_resume() {return 42;};
};
return awaitable{};
}
cppcoro::task<int> foo()
{
int n = co_await make_awaitable();
std::cout << n << std::endl;
}
int main()
{
cppcoro::sync_wait(foo());
std::cout << "Called coro" << std::endl;
return 0;
}
但运行代码会产生断言错误。
coro_test: /usr/include/cppcoro/task.hpp:187: cppcoro::detail::task_promise<T>::rvalue_type cppcoro::detail::task_promise<T>::result() && [with T = int; cppcoro::detail::task_promise<T>::rvalue_type = int]: Assertion `m_resultType == result_type::value' failed.
我做错了什么?
编译器:GCC 10
【问题讨论】:
-
我还有一个协程库,concurrencpp
标签: c++ c++20 c++-coroutine