Stroustrup objects to adding Contracts to C++

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Mon Nov 9 22:39:07 UTC 2026


On 09/11/2026 1:51 PM, Richard (Rikki) Andrew Cattermole wrote:
> For anyone in the know, I'm looking for a couple of books on contracts 
> on the theory side, that isn't too language specific.
> 
> I found good ones on classes, but now I need contracts.

I finally bit the bullet and implemented them.

A key realization occured thanks to Gemini, contract based programming 
is literally just Hoare logic. Specifically Hoare triples.

I know Hoare logic! It is abstract interpretation, wahoo!!!

Anyway, the language feature is pretty straight forward.

An assert or enforce (both language features!) go on to a function or 
class before the open bracket/semicolon.

An invariant is the same, except its used for variable declaration, to 
store state.

I differentiate pre/post conditions based upon what variables they access.
A return, or one declared in the invariant makes it a post condition.

No statements, just expressions.

There is a sanity check LSP solver for classes, it is not allowed false 
positives, and only applies to @safe functions.

```cail
c_contract_tuple(a : int, b : int) : int
     invariant(pa := a, pb : int := b)
     enforce(return == pa + pb)
     enforce(pb == b)
{
     return a + b;
}
```

Strings are supported like D's assert.

assert will not show up in the docs, but enforce will.

I'm pretty happy with this.



More information about the Digitalmars-d mailing list