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 processConst(const auto& rg)
{
  for (const auto& elem : rg) {  // ERROR for coroutines
    //...
  }
}

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

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

int main()
{
  processConst(gen0815());       // ERROR: iterating over a const generator
  processNonConst(gen0815());    // OK
}