capypad
0 day streak
cpp / expert
Snippet

C++20 Coroutines: Minimal Promise Interface

C++20 coroutines are functions that can suspend and resume execution. They are controlled by a 'promise_type' which defines the behavior of the coroutine state machine, such as where it initially suspends.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <coroutine>
#include <iostream>
 
struct Resumable {
struct promise_type {
Resumable get_return_object() { return {}; }
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
 
Resumable simple_coro() {
std::cout << "Step 1\n";
co_await std::suspend_always{};
std::cout << "Step 2\n";
}
 
int main() {
auto handle = simple_coro(); // Suspended at start
}
Breakdown
1
struct promise_type
The mandatory inner struct that acts as the controller for the coroutine's lifecycle.
2
co_await std::suspend_always{};
Suspends the coroutine execution and returns control to the caller.