I've been learning about what's new in C++20 and I'm trying to understand the commonly discussed "Generator" use case of co-routines. I've tried to create a small example here but apologies if there is some mistake:
generator<int> Generate() {
int i = 0;
while(1) {
co_yield i++;
}
}
int main()
{
auto gen { Generate() };
for (int x = 0; x < 10; ++x) {
gen.next();
std::cout << gen.getValue() << std::endl;
}
return 0;
}
But I don't see how this is any different from a function with static variables like:
auto gen() {
static int i = 0;
return i++;
}
int main()
{
for (int x = 0; x < 10; ++x)
std::cout << gen() << std::endl;
return 0;
}
I think I can maybe see how asynchronous I/O is a usecase, especially with the co_await keyword, but for this generator example I'm sure I'm misunderstanding something about how they should be used. I'd be very grateful for any explanation