Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a placeholder return type not allowed for coroutines?

According to C++20's coroutines specification:

A function declared with a return type that uses a placeholder type shall not be a coroutine.

Why is a placeholder type not allowed in such a case?

like image 643
xmllmx Avatar asked Aug 08 '19 15:08

xmllmx


Video Answer


1 Answers

The coroutine machinery that gets used for a particular coroutine is based primarily on the function's return type. The return type is a coroutine future, from which the coroutine logic will deduce the coroutine promise object that will be used to transfer the actual value(s) generated by the coroutine to the caller through the returned future.

This means that of co_await, co_yield, and co_return, none of them actually use the return type of the coroutine (which, btw, is why co_return is spelled differently from return; it has a different meaning and behavior, so it gets a different keyword). co_return and co_yield are not given the future type itself; they're given a type which the promise/future can marshal to the user.

And the co_await expression's type has almost no relation to the promise/future of the coroutine. It's simply a value through which the coroutine can schedule its resumption and from which a value of some arbitrary type can be extracted. The scheduled resumption doesn't really care all that much about the particular future/promise of the current coroutine. You can co_await on a std::future<T>, even if your coroutine's future/promise type isn't std::future of any kind.

So there's no way to deduce what the coroutine's future/promise should be from the expression supplied to any of these keywords. Therefore, you must explicitly specify it.

like image 109
Nicol Bolas Avatar answered Sep 19 '22 04:09

Nicol Bolas