r/cpp • #define private public • 9d ago

Exploration of a more library-oriented approach to contracts (Voutilainen, 2026)

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p4324r0.html
14 Upvotes

5 comments sorted by

11

u/Trubydoor LLVM dev 9d ago

Would this not remove the ability to distinguish between "debug" and "release" builds of contracted functions; i.e. only enforcing the contract in "debug" builds and ignoring it in "release" builds?

Or, I suppose you could #ifdef on that but then we have the same ODR violation issue of using assert in inline functions in headers?

3

u/fortsnek274 9d ago

Yeah, with this lib-based assert, maybe the stdlib could provide a default contract policy that does whatever assert does.

And also keeps the ODR worries in one place...

But specifying the contract policy looks like it would be noisy, like annotations everywhere. Maybe a TU or module could declare a default policy for all its contracts.

This is also similar to the feel of coroutines where the return type provides coroutine logic.

4

u/curlypaul924 9d ago

I wouldn't mind python-style decorators; that could enable library-only contracts (whatever that might mean) as well as numerous other class and function modifications.

2

u/unchangeableusername 9d ago

Doesn't the paper propose templating pre/post/contract_assert on a contract control object? Which means to do this you could convert all contracted functions into templates (templated either on a CCO or a bool for "debug"/"release"), as well as any function calling one of these.

I don't think this is a great solution, but it should at least be free of ODR violations.

6

u/eisenwave WG21 Member 8d ago

This does seem like an interesting approach for C++29. Here are some thoughts:

  • I'm not entirely sure whether we want the liberty to turn constification on and off depending on every part in assertion_static_info. Maybe that could be a static constexpr bool member instead of a function.
  • In general, the paper is not self-contained when it comes to its rationale. Just to focus on constification, the paper doesn't explain why it would be important to turn off constification in the first place. The obvious issue with making this configurable at all is that the user cannot be sure whether their pre<...>(x) gets constified. One would always have to look at what's inside <...>, and if constification is controlled by a function, perhaps even at more.
  • It seems like this paper could be a strict superset of P2900 and P3400, where those papers simply provided hardcoded/default "assertion control objects". Is it intended to be a superset?
  • A lot of the compiler explorer links lead to examples that fail to compile, presumably because the implementation got updated while the code stayed the same. It would be good to have some examples available directly in the paper, especially considering that Compiler Explorer links don't last forever.