C++ 20 New Features
Contents
Coroutines
The "coroutine" concept is a function but unlike a normal function it does not terminate upon return but can suspend it's state and resume the execution later on. We also need to set up code for a coroutine that consists of a class that contains an inner class called a "promise_type" . This dictates the internal behavior of the coroutine.File: co1.cpp
std::suspend_always
await_ready() true -- do not suspend
false suspends --
await_suspend() Does nothing
await_resume() Does nothing
std::suspend_never
await_ready()
await_suspend()
await_resume()
If a function contains the words "co_await" , co_yield" or "co_await"
then that function is a coroutine. However we need to define certain classes
such as "promise_type" in order to get the framework working.
To specify that the 20 version compiler should be used we need
to run the statement:
$ g++ -std=c++20 co1.cpp ; ./a.exe
struct SimpleCoroutine
{
struct promise_type
{
SimpleCoroutine get_return_object()
{
cout << "get_return_object()" << endl ;
return {};
}
std::suspend_never initial_suspend()
{
cout << "initial_suspend()" << endl ;
return {};
}
std::suspend_never final_suspend() noexcept
{
cout << "suspend_never final_suspend()" << endl ;
return {};
}
void return_void()
{
cout << "return_void()" << endl ;
}
void unhandled_exception()
{
cout << "unhandled_exception()" << endl ;
}
};
};