Boost logo

Boost :

From: Martin (m_at_[hidden])
Date: 2002-10-30 06:29:36


Thanks Marc. I think this is a good start. I think however that i have
ommited something.

I am creating the "Special Object" within the function. Actually I am
working on a template for programming by contract.

Q: how many of you people are using programming by contract already in C++?
Q: how many thing they would if there was a practical soution?
Q: do you think there is no practical solution in C++?

Here is a prototype (not a template yet) that illustrates one way that
programming by contract could be imlemented. In this example the pre/post
condition functions get executed in the order that they are declared in the
myContract class. I am looking for ways to automate writing of such code
possibly using templates. Here is the prototype and execution code:

int Function(int vp_Param_int)
{
 class myContract
 {
 public:
  int& vm_Param_int; // reference(s) to input parameter(s)

  //
  // Implement preconditions here
  //
  myContract(int vp_Param_int) : vm_Param_int(vp_Param_int)
  {
   if (vm_Param_int < 0)
   {
    throw "Preconditions error";
   }
  }

  //
  // Implement body here
  //
  void run()
  {
   vm_Param_int = vm_Param_int * 2;
  }

  //
  // Implement postconditions here
  //
  operator int()
  {
   if (vm_Param_int > 100)
   {
    throw "Postcondition error";
   }
   return vm_Param_int;
  }

  //
  // Implement invariant conditions here (if function is a class member)
  //
  ~myContract()
  {
   // If this is a function in a class, we would imlement
   // testing of invariant conditions here. This would require
   // a reference to the object however.
   // Invariants are implemented here because this gets
   // executed even when exceptions are thrown
  }
 };

 myContract aContract(vp_Param_int);
 aContract.run();
 return aContract;
}

int _tmain(int argc, _TCHAR* argv[])
{
 int y = Function(34);
y = Function(-1); // will throw precondition error

y = Function(51); // will throw postcondition error
 return 0;
}

The biggest problem i see is the access to the input parameters from withing
the class. This complicates the code and it means that with larger number of
parameters you have to write too much extra code.

Cheers, Martin.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk