ranges/viewsconst1.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 <print>
#include <vector>
#include <ranges>

void print(const auto& rg)    // note: const reference
{
  for (const auto& elem : rg) {
    std::print("{} ", elem);
  }
  std::println("");
}

int main()
{
  std::vector<int> vec{0, 8, 1, 47, 11, 42, 2};

  // passing containers works fine:
  print(vec);                                              // OK

  // passing non-caching views works fine:
  print(vec | std::views::take(3));                        // OK
  print(vec | std::views::drop(2) | std::views::take(3));  // OK
  print(vec | std::views::transform(std::negate{}));       // OK

  // passing caching views fails:
  auto gt9 = [] (auto val) { return val > 9; };
  print(vec | std::views::filter(gt9));                    // \IBcompile-time ERROR

  // although direct use of the caching view works fine:
  for (int v : vec | std::views::filter(gt9)) {            // OK
    std::print("{} ", elem);
  }
  std::println("");
}