Painless C++ Coroutines-Part 5

11. Coroutine with co_return

ReturnObject foo1(){co_return;     } //co_return w/o an operand
ReturnObject foo2(){co_return value;} co_return w/i an operand

11.1 co_return without an operand

ReturnObject foo(){co_return; } //co_return w/o an operandCompiler stderr:
In function 'ReturnObject foo()':
error: no member named 'return_void'
struct ReturnObject {
struct promise_type {
...
void return_void(){}
};
...
};

11.2 co_return with an operand

ReturnObject foo(){co_return 121; } //co_return with an operandCompiler stderr:
<source>: In function 'ReturnObject foo()':
<source>: error: no member named 'return_value'
struct ReturnObject {
struct promise_type {
...
void return_value(int val){val_ = val;}
};
...
};

12. End of coroutine execution: implicit co_return and final_suspend

struct ReturnObject {
struct promise_type {
...
void return_void(){std::cout << "return_void\n";}
};
...
};
ReturnObject foo(){co_await std::suspend_never{};}
int main(){ foo(); }
stdout
called return_void
int main(){
std::coroutine_handle<PromType> h = foo();
PromType* prom = &h.promise();
/*
call h.resume() many times
*/
if(h.done()){
/*
do something with prom one last time
*/
h.destroy();
}
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gajendra Gulgulia

Gajendra Gulgulia

I'm a backend software developer and from time to time I also like to explore web development