Programming with Contracts in C++

by Christopher Diggins



Listing One



template <typename T>

struct SortableIntArray_contract : public T {

 bool SortRange(int i, int j) {

   // preconditions

   assert(i >= 0);

   assert(i < size());

   assert(j >= i);

   assert(j < size());

   // implementation

   T::SortRange(i, j);

   // postconditions

   // in essence, is this array sorted

   for (int n=i; n < j; n++) {

     assert(get_at(n) <= get_at(n=1));

   }

 }

 int GetAt(int i) {

   // preconditions

   assert(i >= 0);

   assert(i <= size());

   return T::GetAt(i);

 }

 void SetAt(int  i, int x);

   // preconditions

   assert(i >= 0);

   assert(i <= size());

   T::SetAt(i, x);

   // postcondition

   assert(T::GetAt(i) == x);

 }

};



Listing Two 



#ifdef CONTRACT_CHECKING_ON

  typedef SortableIntArray_contract<SortableIntArray_impl>

SortableIntArray;

#else

  typedef SortableIntArray_impl SortableIntArray;

#endif

