Boost logo

Boost :

From: Martin (m_at_[hidden])
Date: 2002-10-27 04:35:24


> Martin wrote:
>
> > Hi
> >
> > Does anybody have any ideas or pointers to how programming by contract
can
> > be implemented easily in C++? I can only think of one non-elegant
solution
> > which involves defining a class in the function that is derived from a
> > template class. something like this (not fully implemented):
>
> [code omitted]
>
> >
> > This example does not handle any arguments for the function. Anyway, I
> > would
> > appreciate any comments or ideas on this topic.
>
> How about a slight change to the run member function:
>
> namespace boost
> {
> template<class result_type>
> class contract
> {
> public:
> result_type run()
> {
> precondition();
> struct postcondition_guard
> {
> explicit postcondition_guard(contract& c) : m_c(c) {}
> ~postcondition_guard() { m_c.postcondition(); }
> constract& m_c;
> };
> postcondition_guard guard;
> return body();
> };
> virtual void precondition() {};
> virtual void postcondition() {};
> virtual result_type body() = 0;
> };
> };
>
> This way, there's no need for the extra copy of the result type.
>
> Also, I think there are const-correctness issues. The above won't work
> if you'd like body to be a const member function. And shouldn't pre- and
> postcondition be const member functions?

Looking at your code gave me the idea that the precondition and the
postcondition could be both implemented in the constructor and a destructor
of some class of which there is an instance in the function. Then there is
really no need for virtual precondition() and postcondition(). Only i am not
sure about unwinding the stack when exceptions are thrown.

>
> Further, is there any reason why you put the assert in pre- and
> postcondition? Couldn't contract just as well do assert(precondition)
> and assert(postcondition)?

i suppose you could. i would expect that typically pre and post conditions
would be throwing exceptions.

>
> This is a start, but I'm sure a better solution will pop-up somewhere
> along this thread. ;)
>
> Regards,
> Dirk Gerrits
>
>
>
> _______________________________________________
> Unsubscribe & other changes:
http://lists.boost.org/mailman/listinfo.cgi/boost
>


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