|
Boost : |
From: Dirk Gerrits (dirk_at_[hidden])
Date: 2002-10-27 13:15:28
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?
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)?
This is a start, but I'm sure a better solution will pop-up somewhere
along this thread. ;)
Regards,
Dirk Gerrits
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk