【问题标题】:Cppcoro not accepting result from an constom awaitable structCppcoro 不接受来自 constom 可等待结构的结果
【发布时间】: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

【问题讨论】:

标签: c++ c++20 c++-coroutine


【解决方案1】:

我认为,问题在于,您将返回类型声明为 task&lt;int&gt;,但实际上并没有 co_return 任何 int

如果你co_returnn,问题会消失吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多