如何解决协程可以返回 std::future 吗? 无法找到此协程的承诺类型
我尝试从 CppCon 演示文稿 https://youtu.be/ZTqHjjm86Bw?t=560
编译协程示例不幸的是编译失败:
$ g++-10 -pedantic -Wall -std=c++20 -fcoroutines main.cpp
main.cpp: In function ‘std::future<int> compute_value()’:
main.cpp:7:16: error: unable to find the promise type for this coroutine
7 | int result = co_await std::async([]
| ^~~~~~~~
一开始演示者警告说他将要演示的只是一个建议。所以这让我很困惑:std::future
可以从协程返回,还是我只是尝试错误地调用它?
完整代码:
#include <coroutine>
#include <iostream>
#include <future>
std::future<int> compute_value(){
int result = co_await std::async([]
{
return 30;
});
co_return result;
}
int main() {
std::cout << compute_value().get() << std::endl;
}
解决方法
C++20 中(基本上1)没有标准库类型来实现必要的协程机制来使协程工作。这包括 std::promise<T>/future<T>
。
不过,您可以为它们编写实现协程机制的包装器。
1:有像 std::suspend_always/never
这样的 support types 有协程机制,但它们并没有像你想象的那样做任何事情。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。