If you have ever used iterators in C# or Visual Basic, then this is essentially the same thing. You would need to enable the new experimental /await
compiler option, same as in the previous blog entry.
std::experimental::generator<int> evens(size_t count) { using namespace std::chrono; for (size_t i = 1; i <= count; i++) { yield i * 2; std::cout << "yielding..." << std::endl; std::this_thread::sleep_for(1s); } }
Calling this method would be fairly straightforward.
void main_yield() { for (auto ev : evens(7)) { std::cout << ev << std::endl; } }
And here’s the expected output.
I added the console output to demonstrate the laziness of the generator.