Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a dynamic number of range adaptors?

I am fairly new to ranges, and I wanted to know if there was a way to apply a dynamic number of range adaptors. I have fiddled around with some code for a while, and I have also done some searching, but to no avail.

#include <iostream>
#include <ranges>

int main() {
    auto output = std::ranges::views::iota(2, 100);

    for (int i = 2; i < 100; i++) {
        output = output | std::ranges::views::filter([i](int num){ return num % i != 0 || num == i; });
    }

    std::cout << "The 10th prime is: " << output[9] << "\n";
}

Essentially, I want something like this, but this gives a compile error (no match for 'operator='). It seems that each application of a range adaptor requires a new type, so we can't dynamically create this range. Is there some way around this?

like image 656
Jack Casey Avatar asked Dec 18 '22 11:12

Jack Casey


1 Answers

For a fixed number like this, it would be possible to use metaprogramming to recursively build the range (although you might hit a template instantiation depth limit). You can do a truly dynamic number by type-erasing the ranges, such that the chain of filters is connected by virtual function calls. The result is slow and the code is painful, but it’s certainly possible.

like image 141
Davis Herring Avatar answered Jan 11 '23 19:01

Davis Herring