coro/genconst.cpp

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

// raw code

#include <generator>

void processRg(auto&& rg)
{
  for (const auto& elem : rg) {  // OK
    //...
  }
}

void processConstRg(const auto& rg)
{
  for (const auto& elem : rg) {  // ERROR for coroutines
    //...
  }
}

std::generator<int> gen0815()
{
  co_yield 0;
  co_yield 8;
  co_yield 15;
}

int main()
{
  processRg(gen0815());          // OK

  processConstRg(gen0815());     // ERROR when using the coroutine
}