How do I compose async operations with when_all/when_any using coroutines in C++?

In C++, composing async operations with `when_all` and `when_any` can be effectively achieved using coroutines. This allows you to manage multiple asynchronous tasks simultaneously. This technique is useful for scenarios where you want to wait for multiple operations to complete before proceeding. Below is an example demonstrating how to use `when_all` and `when_any` with coroutines.

keywords: C++, coroutines, async operations, when_all, when_any
description: This example demonstrates how to compose asynchronous operations using C++ coroutines and the when_all and when_any utilities.
#include <iostream> #include <future> #include <coroutine> #include <vector> using namespace std; // Simulated asynchronous task std::future<int> async_task(int id, int duration) { return std::async(std::launch::async, [id, duration]() { std::this_thread::sleep_for(std::chrono::seconds(duration)); return id * 10; }); } // when_all implementation template <typename... Futures> auto when_all(Futures... futures) { return std::make_tuple(std::move(futures)...); } // Example usage of async operations int main() { auto tasks = when_all(async_task(1, 2), async_task(2, 3), async_task(3, 1)); // Example of waiting for tasks to finish std::apply([](auto&&... futures) { ((std::cout << futures.get() << " "), ...); }, tasks); return 0; }

keywords: C++ coroutines async operations when_all when_any