Boost logo

Boost :

From: Dan W. (danw_at_[hidden])
Date: 2004-01-06 19:21:52


Reece Dunn wrote:
> What about this?:
>
> class derived: public my_class //, public invariants // [1]
> {
> private:
> int c;
> void verify_invariants() const
> {
> ENSURE( c > 0 ); // [4]
> my_class::verify_invariants(); // required! // [2]
> }
> pulbic:
> derived( int _c ): c( _c )
> {
> // FIRST_INVARIANT_CHECK // [3]
> }
> };
>
> [1] Not needed because we know that it derives from invariants.
> [2] Needed to ensure my_class invariants hold
> [3] Not needed -- initiated in my_class

[3] needed, or something like it, because I could pass -1 to the ctor
of derived, and the first invariant would not check it. But I was in
a double-bind: If I called first invariant check in derived, the problem
then was that it would find the inherited boolean "enabled_" already
initialized.

I found the solution though, and it's to inherit invariants again, in a
derived class, but to templetize invariants by derived. That way I get
a new boolean (I made it a char now) each time I inherit invariants
again. Works like a charm; I just tested it with multiple inheritance.
The only small price to pay is that each derived class must have a

typedef my_name type;

> If you have a complex MI framework with thousands of classes, managing
> the code would become very difficult. As such, I am now of the feeling
> that a language extension would be best (i.e. the compiler can deduce
> the correct code). Thus, you could have something like (depending on
> what the C++0x invariant proposal looks like):
>
> class my_class
> {
> private:
> int a;
> int b;
> __invariant( a + b == 5 );
> public:
> void set( int _a, int _b )
> {
> __precondition( _a > 0 );
> }
> };
>
> And can add a check for invariant capabilities thus:
>
> #if COMPILER_SUPPORTS_DBC
> # define BOOST_INVARIANT(x) __invariant(x)
> #else
> # define BOOST_INVARIANT(x)
> #endif

You're right about the need for language extensions for DBC. Invariants
is easy to do through a library; but preconditions and postconditions
are IMHO impossible to do in the language. At least not in any semblance
of an elegant way.

And by the way, couldn't C++ use a keyword 'type', meaning typeof(this)?

(I'll post the new version in two minutes.)

Cheers!


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