Help with Coroutines
Hello friends,
How would be the correct translation of this code to C++?
1 2 3 4 5
|
public IEnumerable<int> Sequence(int min, int max) {
for (int x = min; x <= max; x++) {
yield return x;
}
}
|
Thank you!
C++ does not have coroutines.
You should just rewrite the code to not use "yield".
If you need help with that, post the entire code.
EDIT: As a simple emulation, you could do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
class Sequence {
int m_first, m_last, m_inc;
bool m_done;
public:
Sequence(int first, int last){
set(first, last);
}
void set(int first, int last) {
m_first = first;
m_last = last;
m_inc = first > last ? -1 : 1;
m_done = false;
}
bool yield(int &ret) {
if (m_done)
return false;
if (m_first == m_last)
m_done = true;
ret = m_first;
m_first += m_inc;
return true;
}
};
int main() {
Sequence seq(10, 20);
for (int n; seq.yield(n); )
std::cout << n << ' ';
std::cout << '\n';
seq.set(20, 10);
for (int n; seq.yield(n); )
std::cout << n << ' ';
std::cout << '\n';
}
|
Last edited on
Thanks for the reply tpb!
Topic archived. No new replies allowed.