1

I have a vector of ints and I'd like to print it as a comma separated list. I would like to do it using ranges and since clang doesn't the necessary features I'd like to use rangesv3:

https://godbolt.org/z/esM5sPe6a

    std::vector<int> v{6, 2, 3, 4, 5, 6};


    // doesn't compile
    std::cout << (
        v | ranges::transform_view( [](int val){return fmt::format("{}",val);}) 
          | ranges::join_with_view(", ")
          | ranges::to<std::string>)
    ) << std::endl;

This doesn't compile and gives me some template deduction error. However

    // works
    auto a = ranges::transform_view(v,  [](int val){return fmt::format("{}",val);});
    std::cout << (ranges::join_with_view(a, ", ") | ranges::to<std::string>) << std::endl;

If I don't pipe v in, but instead pass it as an argument and do the same for the transformed range it works.

What am I doing wrong? I am the only one likes ranges, but finds the cumbersome due to these kind of problems?

Stein
  • 3,179
  • 5
  • 27
  • 51
  • To help people answer your question, you'll need to be more specific about the error. Please [edit] your post to incorporate the exact errors you get from your [mcve] (preferably using copy+paste to avoid transcription errors). – Toby Speight Aug 31 '23 at 13:24
  • Also, your code is incomplete; in particular, it seems to be missing a `main()` function and at least one `#include`. Please [edit] your code so it's a [mcve] of your problem (including any necessary inputs, but preferably not needing any), then we can try to reproduce and solve it. You should also read [ask]. – Toby Speight Aug 31 '23 at 13:25

1 Answers1

2

ranges::transform_view is a class, which is an implementation detail of the range adaptor ranges::views::transform.

Only range adaptors can be composed via the pipe operator, so those under the namespace ranges::views are the ones you should use, for example:

std::cout << (
    v | ranges::views::transform( [](int val){return fmt::format("{}",val);}) 
      | ranges::views::join(", ")
      | ranges::to<std::string>
) << std::endl;

In general, you should always prefer views::meow.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90