协程能不能还STD::未来?(找不到此协程的承诺类型) [英] Can coroutine return std::future? (unable to find the promise type for this coroutine)

查看:41
本文介绍了协程能不能还STD::未来?(找不到此协程的承诺类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试从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:有support typesLIKEstd::suspend_always/never具有协程机器,但它们的功能并不像您想象的那样。

这篇关于协程能不能还STD::未来?(找不到此协程的承诺类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆