coyield2.cpp

The following code example is taken from the book
C++20 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2021
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License


#include "intrange.hpp"
#include <iostream>
#include <vector>
#include <thread>

template<typename T>
IntRange loopOver(const T& coll) 
{
  // coroutine that iterates over the elements of a collection:
  for (auto elem : coll) {
    std::cout << "- suspend" << '\n';
    co_yield elem;  // calls yield_value(elem) on promise
    std::cout << "- resume" << '\n';
  }
}

int main()
{
  using namespace std::literals;
  
  // define generator that yields the elements of a collection:
  std::vector<int> coll{0, 8, 15, 33, 42, 77};
  IntRange gen = loopOver(coll);

  // loop to resume the coroutine until there is no more value:
  std::cout << "start loop:\n";
  for (const auto& val : gen) {
    std::cout << "value: " << val << '\n';
    std::this_thread::sleep_for(1s);
  }
}