coro/genstringview.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 <string>
#include <string_view>
#include <print>
#include <vector>
#include <generator>

std::generator<std::string_view, std::string> genStringViews(auto& coll)
{

  for (std::string_view sv : coll) {
    co_yield sv;
  }
}

int main()
{
  std::vector<std::string> vec{"tic", "tac", "toe"};

  for (auto&& s : genStringViews(vec)) {
    static_assert(std::same_as<decltype(s), std::string_view&&>);
    std::println(" main(): s: {}", s);
  }
}