c-resources/CPlusPlus20ForProgrammers-m.../examples/libraries/generator
davoudn 754b4098da some changes to chapter 6 2024-04-08 23:45:18 -07:00
..
.github/workflows some changes to chapter 6 2024-04-08 23:45:18 -07:00
cmake some changes to chapter 6 2024-04-08 23:45:18 -07:00
include/tl some changes to chapter 6 2024-04-08 23:45:18 -07:00
tests some changes to chapter 6 2024-04-08 23:45:18 -07:00
.gitattributes some changes to chapter 6 2024-04-08 23:45:18 -07:00
.gitignore some changes to chapter 6 2024-04-08 23:45:18 -07:00
CMakeLists.txt some changes to chapter 6 2024-04-08 23:45:18 -07:00
CMakeSettings.json some changes to chapter 6 2024-04-08 23:45:18 -07:00
COPYING some changes to chapter 6 2024-04-08 23:45:18 -07:00
README.md some changes to chapter 6 2024-04-08 23:45:18 -07:00
vcpkg.json some changes to chapter 6 2024-04-08 23:45:18 -07:00

README.md

generator

Single-header, ranges-compatible generator type built with C++20 coroutines.

Documentation Status

A generator allows implementing sequence producers which are terse and avoid creating the whole sequence in memory.

For example, if you were to need a sequence of the first n integers, you could generate a std::vector of them. This implementation would be simple, but would have to produce the whole sequence in memory. To avoid this, you could instead write an iterator or range which generates them lazily. However, writing iterators and ranges comes with a lot of boilerplate. Generators have the benefits of both:

tl::generator<int> firstn(std::size_t n) {
   for (auto i = 0; i < n; ++i) {
      co_yield i;
   }
}

You could then use this generator like so:

for (auto i : firstn(10)) {
   std::cout << i;
}

Generators can also create infinite sequences:

tl::generator<int> iota(int i = 0) {
  while(true) {
    co_yield i;
    ++i;
  }
}

You can then pipe this to a range to process it:

for (auto i : iota() | std::views::take(10)) {
   std::cout << i;
}

Compiler support

tl::generator has been tested on Visual Studio 2019 version 16.9 and GCC 10.


CC0

To the extent possible under law, Sy Brand has waived all copyright and related or neighboring rights to the optional library. This work is published from: United Kingdom.