|
Boost : |
From: Maksym Motornyy (mmotorny_at_[hidden])
Date: 2005-06-02 04:03:24
Hi all,
As of version 2.0 C# will have yield statement. It intended for
simplifying iterator development. Yield suspends execution of iterator
code and resumes it on next increment. Thus complex traversal iterators
are much easier to write in natural loop-like form instead of unroll them.
Consider following example (C#):
public IEnumerator< int > GetEnumerator()
{
for ( int i = 1; i < 4; ++i )
for ( int j = 1; j < 4; ++i )
yield return i * j;
}
Such iterator will generate following sequence: 1 2 3 2 4 6 3 6 9.
The same code in C++ (using my library) will look like:
class simple_generator
{
public:
YIELD_BEGIN_WITH_CTOR( simple_generator, int )
YIELD_FOR_0( i = 1, i < 4, ++i )
YIELD_FOR_1( j = 1, j < 4, ++j )
YIELD_RETURN( i * j )
YIELD_END_FOR_1
YIELD_END_FOR_0
YIELD_END
private:
int i;
int j;
};
int main( int, char ** )
{
for ( simple_generator g; !g.at_end(); ++g )
cout << *g << " ";
return 0;
}
Have a look at few more examples:
Example 1:
YIELD_BEGIN_WITH_CTOR( simple_generator, string )
YIELD_RETURN( "Hello," )
YIELD_RETURN( "world!" )
YIELD_END
Will print "Hello, world!" in two iterations with the above main() function.
Example 2:
YIELD_BEGIN_WITH_CTOR( simple_generator, int )
YIELD_FOR( i = 0, i < 10, ++i )
YIELD_IF( i % 2 == 0 )
YIELD_CONTINUE
YIELD_END_IF
YIELD_RETURN( i )
YIELD_END_FOR
YIELD_END
Will print "1 3 5 7 9 ".
If anyone interested in such thing?
Sincerely yours,
Maksym Motornyy.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk