// WARNING: Requires exceptions (use g++ -fhandle-exceptions) #include // GENERIC-BRAND DEVICE CLASS class Device { public: Device(void) : myActive(false) {} bool Activate(void) { return myActive = true; } bool Active(void) const { return myActive; } private: bool myActive; }; // EXCEPTIONS struct PoolOverflow { PoolOverflow(const Device&) { cout << "threw PoolOverflow()" << endl; } }; struct BadIndex { BadIndex(int index) { cout << "threw BadIndex(" << index << ")" << endl; } }; // THRESHOLDED POOL CLASS WITH DIRECT ACTIVATION OF DEVICES IN THE POOL class Pool { public: Pool(void) : myActives(0) {} class DeviceProxy { public: DeviceProxy(Device& dev, Pool& pool) : myRef(dev), myPool(pool) {} void operator=(const Device& newdev) { int delta = (newdev.Active()?1:0)-(myRef.Active()?1:0); if (myPool.myActives+delta >= myPool.THRESHOLD) { throw PoolOverflow(newdev); } myPool.myActives+= delta; myRef = newdev; } bool Activate(void) { int delta = 1-(myRef.Active()?1:0); if (myPool.myActives+delta >= myPool.THRESHOLD) { return false; } myPool.myActives+= delta; myRef.Activate(); return true; } private: Device& myRef; Pool& myPool; }; friend class DeviceProxy; DeviceProxy operator[](int index) { if (index<0||index>=MAXDEVICES) { throw BadIndex(index); } return DeviceProxy(myDevice[index],*this); } private: enum { MAXDEVICES = 100, THRESHOLD = 20 }; Device myDevice[MAXDEVICES]; // DEVICES IN THIS POOL int myActives; // HOW MANY ARE ACTIVE? }; int main(void) { Pool pool; for (int i=0; i<100; i++) { cout << "activating pool[" << i << "]" << endl; if (!pool[i].Activate()) { cout << "Could not activate pool[" << i << "]" << endl; } } return 0; }