-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerator.cpp
More file actions
46 lines (38 loc) · 1.05 KB
/
generator.cpp
File metadata and controls
46 lines (38 loc) · 1.05 KB
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
40
41
42
43
44
45
46
/*
* 使用无栈协程实现仿python的range生成器
*/
#include "coroutine_utils.hpp"
#include <iostream>
template<class T>
class range : public coroutine_base {
public:
explicit range(T end) : _begin(0), _end(end), _step(1) {}
range(T begin, T end) : _begin(begin), _end(end), _step(1) {}
range(T begin, T end, T step) : _begin(begin), _end(end), _step(step) {}
T operator()() {
COROUTINE_BEGIN
for (_i = _begin; _i < _end; _i += _step) {
COROUTINE_YIELD(_i);
}
COROUTINE_RETURN(-1);
COROUTINE_END
}
private:
T _begin, _end, _step;
T _i;
};
int main() {
{
std::cout << "range(10): " << std::endl;
auto r = range(10);
for (auto i = r(); !r.done(); i = r()) std::cout << i << " ";
std::cout << std::endl;
}
{
std::cout << "range(1.2, 12.3, 2.3): " << std::endl;
auto r = range(1.2, 12.3, 2.3);
for (auto i = r(); !r.done(); i = r()) std::cout << i << " ";
std::cout << std::endl;
}
return 0;
}