如何解决Cppcoro 不接受来自 constom 可等待结构的结果
我决定编写自己的 awaitable 以便加载器了解 C++ 协程的工作原理。现在,我想构建自己的结构,相当于:
cppcoro::task<int> bar()
{
co_yield 42;
}
这是我在阅读 CppReference's coroutine page 后想到的。其中声明最后,awaiter.await_resume() 被调用,其结果是整个 co_await expr 表达式的结果。 我认为改变 await_resume()
的返回类型足以给两者bar
和 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
解决方法
我认为问题在于,您将返回类型声明为 task<int>
,但实际上并没有 co_return
任何 int
。
如果你co_return
n,问题会消失吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。