VC++ 2015 – Lazy generators

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.

yield_demo_cpp

I added the console output to demonstrate the laziness of the generator.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s