summaryrefslogtreecommitdiff
path: root/doc/generator.cpp
blob: 6c64f80a6f26602d35a24f962119061ee4a6372b (plain)
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
/*
 * sample.
 *
 * Something more or less like Python generators.
 */
#include <cstdlib>
#include <cstdio>
template<class base> class fi /* filler_iterator */ {
        private:
        base &parent;
        public:
        fi(base &p) : parent(p) {};
        bool operator!=(const fi &) { return parent.has_more(); };
        const fi &operator++(void) { return *this; };
        int operator*(void) { return parent.yield(); };
};

class rdgen {
        private:
        unsigned int remaining;

        public:
        rdgen(unsigned int x) {
                remaining = x;
        };
        bool has_more(void) {
                return remaining > 0;
        };
        int yield(void) {
                --remaining;
                return rand();
        };

        fi<rdgen> begin(void) { return fi<rdgen>(*this); };
        fi<rdgen> end(void) { return fi<rdgen>(*this); };
};

int main(int argc, const char **argv)
{
        for (auto x : rdgen(argc))
                printf("%d\n", x);
        return 0;
}