I have tried to compile coroutine example from the CppCon presentation https://youtu.be/ZTqHjjm86Bw?t=560
Unfortunately compilation fails:
$ 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([]
| ^~~~~~~~
At the beginning presenter warns that what he is about to present is just a proposal. So it makes me confused: can std::future
be return from a coroutine, or do I just try to call it incorrectly?
Full code:
#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;
}
There are (basically1) no standard library types in C++20 that implement the necessary coroutine machinery to make coroutines work. This includes std::promise<T>
/std::future<T>
.
You could write wrappers for them that implement the coroutine machinery though.
1: There are support types like std::suspend_always
/std::suspend_never
which have coroutine machinery, but they don't really do anything like what you're thinking of.