Consider the following example:
SomeContainerObject Elements;
MyIterator iter(Elements);
while(iter.hasNext()){
Element e = iter.next();
doSomething(e);
}
SomeContainerObject Elements;
MyIterator iter(Elements);
while(iter.hasNext()){
Element e = iter.next();
doSomething(e);
}
To copy to clipboard, switch view to plain text mode
Isn't this exactly what is searched for? And this is exactly a typical iterator. Of course hasNext() and next() have to be implemented in such a way that they perform the same function what the yieldable function does.
What is vital is that the iterator keeps an internal state of "index" in the iterated object. Then it's just a matter of generating elements. Of course the object doesn't even have to be a container - in that case the iterator becomes a simple generator function, like this:
class Generator {
public:
Generator(int start){
m_curr = start;
}
bool hasNext(){ return true; /* neverending story */ }
int next(){ return -(m_curr++); }
private:
int m_curr;
}
class Generator {
public:
Generator(int start){
m_curr = start;
}
bool hasNext(){ return true; /* neverending story */ }
int next(){ return -(m_curr++); }
private:
int m_curr;
}
To copy to clipboard, switch view to plain text mode
The above object keeps returning negations of increasing numbers starting from the number passed as the argument for the generator. It's similar to:
int fun(int s){
int x = s;
while(1){
int r = -x;
x = x+1;
yield r;
}
}
int fun(int s){
int x = s;
while(1){
int r = -x;
x = x+1;
yield r;
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks