public void Consumer() { foreach(int i in Integers()) { Console.WriteLine(i.ToString()); } } public IEnumerable<int> Integers() { yield return 1; yield return 2; yield return 4; yield return 8; yield return 16; yield return 16777216; }
Is there a way with template trick (or other) to get the same syntax in c++?
What is the use of yield return in C#? CsharpServer Side ProgrammingProgramming. Yield keyword helps to do custom stateful iteration over a collection. Meaning when we use yield keyword the control moves back and forth from the caller function to source and vice versa.
You use a yield return statement to return each element one at a time. The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method.
The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it.
The yield return statement is special; it is what actually tells Unity to pause the script and continue on the next frame. There are a number of ways that can be used to yield return; one of which is to create an instance of the WaitForSeconds class.
Take a look at boost::Coroutine. It does what you want. http://www.crystalclearsoftware.com/soc/coroutine/index.html#coroutine.intro
Example from tutorial
http://www.crystalclearsoftware.com/soc/coroutine/coroutine/tutorial.html
int range_generator(generator_type::self& self, int min, int max) { while(min < max) self.yield(min++); self.exit(); }
You can always code this by hand. Truthfully, yield
really seems like sugar coating to me (and co-routines too).
What a coroutine is, really ? Some state bundled up together with:
In C++, it's called an InputIterator
, and can be arbitrarily fat.
So, it's true that the syntax won't be as pretty, but this should do, just with the Standard Library:
static std::array<int, 6> const Array = {{1, 2, 4, 8, 16, 16777216}}; class Integers: public std::iterator<std::input_iterator_tag, int, ptrdiff_t, int const*, int> { public: Integers(): _index(0) {} operator bool() const { return _index < Array.size(); } Integers& operator++() { assert(*this); ++_index; return *this; } Integers operator++(int) { Integers tmp = *this; ++*this; return tmp; } int operator*() const { assert(*this); return Array[_index]; } int const* operator->() const { assert(*this); return &Array[_index]; } private: size_t _index; }; // class Integers
And obviously, since you decide exactly what state is stored, you decide if all is pre-computed or if part (or whole of it) is lazily computed, and possibly cached, and possibly multi-threaded, and ... you got the idea :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With