协程可以返回 std::future 吗?(无法找到该协程的承诺类型)

use*_*761 4 c++ future coroutine c++20 c++-coroutine

我尝试编译 CppCon 演示文稿中的协程示例https://youtu.be/ZTqHjjm86Bw?t=560

\n

在此输入图像描述

\n

不幸的是编译失败:

\n
$ g++-10 -pedantic -Wall -std=c++20 -fcoroutines main.cpp \nmain.cpp: In function \xe2\x80\x98std::future<int> compute_value()\xe2\x80\x99:\nmain.cpp:7:16: error: unable to find the promise type for this coroutine\n    7 |   int result = co_await std::async([]\n      |                ^~~~~~~~\n
Run Code Online (Sandbox Code Playgroud)\n

演讲者一开始就警告说,他将要演讲的只是一个提案。所以这让我很困惑:可以吗?std::future从协程返回,还是我只是尝试错误地调用它?

\n

完整代码:

\n
$ g++-10 -pedantic -Wall -std=c++20 -fcoroutines main.cpp \nmain.cpp: In function \xe2\x80\x98std::future<int> compute_value()\xe2\x80\x99:\nmain.cpp:7:16: error: unable to find the promise type for this coroutine\n    7 |   int result = co_await std::async([]\n      |                ^~~~~~~~\n
Run Code Online (Sandbox Code Playgroud)\n

Nic*_*las 6

C++20 中(基本上1)没有标准库类型来实现使协程工作所需的协程机制。这包括 std::promise<T>/future<T>

不过,您可以为它们编写包装器来实现协程机制。

1:有些支持类型具有std::suspend_always/never协程机制,但它们实际上并没有像您想象的那样做任何事情。

  • @BartLouwers:问题是询问协程是否与“std::future”一起使用。如何在不提及“std::future”的情况下回答有关“std::future”功能的问题?此外,说协程“与多线程无关”是相当不准确的,因为协程的异步恢复是该功能的“主要”设计目标。 (5认同)