Double-Bounded Safe Array
#ifndef _BSAFEARR_H_ #define _BSAFEARR_H_ #include <iostream> #include <stdexcept> #include "gsafearr3.h" using namespace std; /* * Bounded safe integer array: Based on the SafeIntArr class in the copying * group. */ template <typename T> class BoundedSafeArr: public SafeArr<T> { public: // Create a bounded array, with both a lower and upper subscript bound. BoundedSafeArr(int lb, int ub): SafeArr<T>(ub-lb+1) { lower = lb; } // Convenience constructor when you need the common case of // lower bound zero. BoundedSafeArr(int size): SafeArr<T>(size) { lower = 0; } // Wrappers to adapt the base class store and fetch methods. They // catch the out_of_range from the base class mainly to re-write // the error message for the double bounds. void store(int pos, const T &tostore) { try { // This calls the base class store. Unfortunately, // C++ does not have super. SafeArr<T>::store(pos - lower, tostore); } catch(out_of_range &e) { // Re-write the error message. The call to size() // needs a qualifier because we're using templates. // Don't know why. Not needed in a plain class since // we don't have a size() in this class. throw out_of_range("gsafearr3 store at " + to_string(pos) + " out of range " + to_string(lower) + ".." + to_string(SafeArr<T>::size()+lower-1)); } } // Fetch using the bounds. Again, we catch to re-write the message. T fetch(int pos) const { try { return SafeArr<T>::fetch(pos - lower); } catch(out_of_range &e) { throw out_of_range("gsafearr3 fetch at " + to_string(pos) + " out of range " + to_string(lower) + ".." + to_string(SafeArr<T>::size()+lower-1)); } } // This must be repeated, since the base class version will not call // the base class one-argument fetch. (Java would just work, and // we wouldn't need this. Long story.) void fetch(int pos, T &fetched) const { fetched = fetch(pos); } // The size() method is inherited and works fine without change. // We add these extractors to recover the specific bounds. int get_low() const { return lower; } int get_hi() const { return lower + SafeArr<T>::size() - 1; } private: // Lower bound. int lower; }; #endif