I'm trying to learn C++ ranges. As far as I can see, the simplest (and the only, short of implementing a custom range view class) way to create a range view object that generates a custom sequence is to use C++23' std::generator<>
:
std::generator<char> letters_gen(char start)
{
for (;;) co_yield start++;
}
How do I use a std::generator
object (as created by invoking letters_gen()
) in multiple expressions involving range operations? E.g. if I want to collect 10 letters into a vector, and then 15 more letters into another vector:
int main()
{
auto letters = letters_gen('a');
auto x = letters | std::views::take(10) | std::ranges::to<std::vector>();
auto y = letters | std::views::take(15) | std::ranges::to<std::vector>();
}
This does not compile:
main.cc:150:26: error: no match for ‘operator|’ (operand types are ‘std::generator<char>’ and ‘std::ranges::views::__adaptor::_Partial<std::ranges::views::_Take, int>’)
What is the proper way, if any, to achieve the desired effect?
std::ranges::iota
might work for you. – Fritillary