3

This works as expected:

#include <range/v3/all.hpp>
#include <iostream>

int main() {
  auto chunklist = ranges::views::ints(1, 13) | ranges::views::chunk(4);
  for (auto rng : chunklist) {
    for (auto elt : rng)
      std::cout << elt << " ";    
    std::cout << std::endl;
  }
}

On the screen:

1 2 3 4
5 6 7 8
9 10 11 12

But if I try to substitute ranges::copy instead of for loop, I am getting compilation error

  auto chunklist = ranges::views::ints(1, 13) | ranges::views::chunk(4);
  for (auto rng : chunklist) {
    ranges::copy(rng, std::ostream_iterator<int>{std::cout, " "}); // FAIL
    std::cout << std::endl;
  }

Compilation error is rather obscure. I will not give full text here but looks like almost all concepts failed:

note:   constraints not satisfied
...
note: within '...' CPP_concept_bool weakly_incrementable =
...
note: within '...' CPP_concept_bool semiregular =
...
note: within '...' CPP_concept_bool default_constructible =
...
note: within '...' CPP_concept_bool constructible_from =
...
confused by earlier errors, bailing out

I am using gcc-9.3 with options:

g++ -fconcepts --std=c++2a chunksimplified.cc

And top of trunk range-v3 library from github

How shall I modify code in order to use explicit algorithm instead of raw loop?

Konstantin Vladimirov
  • 6,791
  • 1
  • 27
  • 36

1 Answers1

3

The issue is not with ranges::copy, it's just that ranges::views don't play nicely with std::ostream_iterator.

You can just use ranges::ostream_iterator instead:

ranges::copy(rng, ranges::ostream_iterator<int>{std::cout, " "});  

Here's a working demo.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • Thanks it works. Didn't know about custom ostream_iterator in ranges namespace. Looks like C++20 only have std version. – Konstantin Vladimirov May 10 '20 at 02:13
  • 1
    Honestly, I haven't tried any of c++20 ranges stuff yet. Don't expect to be able to use *too many* ranges features in c++20. They'll get added, but it'll take time. – cigien May 10 '20 at 02:16