C++ で Algorithm - 0と1を次々と返す簡単なお仕事

http://blog.livedoor.jp/dankogai/archives/51512419.html を見て。

まず素直に。

/*
 *  class flipflop
 *
 *  written by janus_wel<janus.wel.3@gmail.com>
 *  This source code is in public domain, and has NO WARRANTY.
 * */

#include <iomanip>
#include <iostream>

class flipflop {
    private:
        bool state;

    public:
        flipflop(void) : state(true) {}
        bool operator ()(void) {
            state = !state;
            return state;
        }
};

int main(void) {
    flipflop ff;

    std::cout << std::boolalpha
        << ff() << "\n"
        << ff() << "\n"
        << ff() << "\n"
        << ff() << "\n"
        << std::endl;

    return 0;
}

istream を使って。微妙。

/*
 *  flipflop istream
 *
 *  written by janus_wel<janus.wel.3@gmail.com>
 *  This source code is in public domain, and has NO WARRANTY.
 * */

#include <iomanip>
#include <iostream>
#include <iterator>
#include <algorithm>

class flipflopstreambuf : public std::streambuf {
    private:
        static const unsigned int numof_state = 2;
        char state[numof_state];

    public:
        flipflopstreambuf(void) {
            state[0] = 1;
            state[1] = 0;
            setg(state, state, state + numof_state);
        }

    protected:
        int_type underflow(void) {
            setg(eback(), eback(), egptr());
            return traits_type::to_int_type(*gptr());
        }
};

struct iflipflopstream : public std::istream {
    iflipflopstream(void) : std::istream(new flipflopstreambuf()) {}
    ~iflipflopstream(void) { delete rdbuf(); }
};

inline iflipflopstream&
operator >>(iflipflopstream& i, bool& m) {
    m = static_cast<bool>(i.get());
    return i;
}

int main(void) {
    iflipflopstream ffin;

    std::cout << std::boolalpha;

    // the use of a bit of circuity form
    bool f;

    ffin >> f;
    std::cout << f << "\n";

    ffin >> f;
    std::cout << f << "\n";

    ffin >> f;
    std::cout << f << "\n";

    ffin >> f;
    std::cout << f << "\n";

    // easy to use but bad readability
    std::istream_iterator<char> iitr(ffin), end;
    std::cout
        << static_cast<bool>(*iitr++) << "\n"
        << static_cast<bool>(*iitr++) << "\n"
        << static_cast<bool>(*iitr++) << "\n"
        << static_cast<bool>(*iitr++) << "\n"
        << std::endl;

    // simple but endless
    std::ostream_iterator<bool> oitr(std::cout, "\n");
    std::copy(iitr, end, oitr);

    return 0;
}