Listing 4: Subwindow iterator design.

template<size_t _SubWidth, size_t _SubHeight, typename _Tp>
class SubWindow: public std::iterator<heavy_forward_iterator_tag, _Tp>
{
  public:
  // the nested iterator definition
  class iterator: public std::iterator<std::forward_iterator_tag, _Tp>  {
    // dereference, add padding if necessary
    inline _Tp operator*(void) const {        
      if ((x_ < 0) || (y_ < 0) || (x_ >= width_) || (y_ >= yOffImage_)) {
        return 0;
      }
      return begin_[y_ + x_];
    }
    // advance preserving spatial location in image
    inline iterator & operator ++(void) {
      x_ += 1;
      if (x_ > stopX_) {
        x_  = startX_;
        y_ += width_;
      }
      return *this;
    }
    // get the lightweight proxy
    proxy_iterator operator&(void)
    {
      return proxy_iterator(this);
    }
    // remaining methods and  data members omitted for brevity
    // ...
  };
  // define a proxy for reducing copy overhead
  class proxy_iterator: public std::iterator<std::forward_iterator_tag, _Tp> {
    // pass operation along to addressee
    inline proxy_iterator& operator++(void)  {
      addressee_->operator++();
      return *this;
    }
    // remaining methods and  data members omitted for brevity
    // ...
  };
  // Access the iterator pair. Note returning a reference for efficiency
  inline iterator &begin()  {
    return begin_;
  }
  inline iterator &end()  {
    return end_;
  }
  // set the position in the larger image (see downloadable code)
  inline void reset(size_t x, size_t y);
  // constructor caches the data pointer and dimensions
  SubWindow(_Tp *in, int width, int height);
private:
  // current location
  iterator begin_;
  iterator end_;
};