ちと長くなってしまった。
#include <limits> template<int N> class BitArray { public: typedef unsigned int ValueType; static const int BitsPerValue = std::numeric_limits<ValueType>::digits; static const int ArraySize = (N + BitsPerValue - 1) / BitsPerValue; inline static ValueType BitOf(int n) { return ValueType(1) << n; } BitArray() { clear(); } void set(int index) { if((0 <= index) && (index < N)) { values_[index / BitsPerValue] |= BitOf(index % BitsPerValue); } } void unset(int index) { if((0 <= index) && (index < N)) { values_[index / BitsPerValue] &= ~BitOf(index % BitsPerValue); } } void clear() { for(int i = 0; i < ArraySize; ++i) { values_[i] = 0; } } bool at(int index) const { if((0 <= index) && (index < N)) { return (values_[index / BitsPerValue] & BitOf(index % BitsPerValue)) != 0; } else { return false; } } class Bit { public: Bit(BitArray* bitArray, int index) : bitArray_(bitArray), index_(index) { } Bit& operator = (bool f) { if(f) bitArray_->set(index_); else bitArray_->unset(index_); return *this; } private: BitArray* bitArray_; const int index_; }; Bit operator [] (int index) { return Bit(this, index); } const bool operator [] (int index) const { return at(index); } private: ValueType values_[N]; };