2

I am trying to learn std::ranges library that is introduced in C++20 but I'm unable to get it working even for this small example.

#include <iostream>
#include <vector>
#include <ranges>

template<typename View>
requires std::ranges::view<View>
void print(View v)
{
    if (v.empty())
    {
        std::cout << "\n";
        return;
    }

    std::cout << v[0] << " ";
    print(v | std::views::drop(1));
}

int main()
{
    std::vector<int> v{1, 2, 3, 4};
    print(v | std::views::all);
}

You can check at godbolt that it does not compile.

In my local setup I get around 1000 lines long error message about recursive instantiation of templates.

I know I can do it iteratively, but that's not the point, I want to know why this is not working and how can I make it work. Thanks.

Gaurish Gangwar
  • 395
  • 4
  • 14
  • It can't compile because it leads to infinite template function instantiations. – 273K Sep 26 '22 at 17:27
  • 1
    Every instance of your `print` function includes code to call another, different different `print` function. The early `return` does not prevent the rest of that function from being compiled. – Drew Dormann Sep 26 '22 at 17:30
  • It turned out that the question has already been asked but I'm not deleting it because the title of original question is really advanced for someone starting with C++ ranges, maybe that's why I could not find it. For those looking for answer, I have found a way to make it work and have posted it as the answer to [original question](https://stackoverflow.com/questions/61867635/recursive-application-of-c20-range-adaptor-causes-a-compile-time-infinite-loop). – Gaurish Gangwar Sep 26 '22 at 18:25

0 Answers0