C++ Logo

std-proposals

Advanced search

Re: [std-proposals] P4021 compile_assert draft proposal for feedback

From: Jonathan Grant <jg_at_[hidden]>
Date: Tue, 3 Mar 2026 09:23:45 +0000
On 22/02/2026 12:35, Jonathan Wakely wrote:
>
>
> On Sun, 22 Feb 2026, 11:26 Marcin Jaczewski via Std-Proposals, <std-proposals_at_[hidden] <mailto:std-proposals_at_[hidden]>> wrote:
>
>
>
> How this is better than possible:
>
> ```
> contract_assert [[ prove_this_at_compile_time ]] (expr);
> ```
>
> or even better make it precondition:
>
> ```
> void foo() pre [[ prove_this_at_compile_time ]] (expr)
> {
> }
> ```
>
> And have a special compilation mode that try enforce this at compilation time,
> and in other cases it fallback to normal contract handling.
>
>
>
> Yes, I think "make it ill-formed at compile-time when optimizing, otherwise add a runtime assertion" would be something people want to do.
>

That's a good point, if compile_assert() is in an unoptimized build a user could fall back on a runtime assert(). Although once the constraint is validated in an optimized build maybe the runtime assert() fallback isn't needed?

Perhaps debug libraries may use slightly different implementations, so an issue may present itself. Could run a test suite with it as assert() to be sure. Good to validate both runtime and compile time, compare and contrast any differences.

> With the current proposal, that's awkward. You would need to do:
>
> #ifdef __OPTIMIZING__ && __ENABLE_COMPILE_ASSERT__
> compile_assert(cond);
> #else
> assert(cond);
> #endif
>
> or wrap that into your own macro. But that depends on a non-standard macro which is compiler-dependent. It would be easier if the feature defined something that you could check to see if the compile_assert is actually enabled.

Good suggestion, I added COMPILE_ASSERT_ACTIVE to the proposal.

>
>
> Also, the more I look at code examples using this, the less I like the name. It didn't tell me what it does. All assertions are compiled, what is a "compile assert"? Assert that something compiles, i.e. is syntactically valid? That's what a requires expression does, but it's not what this does.

I did think of a few different names before settling on compile_assert() as I felt that as static_assert is also evaluated at compile time I could call my proposal an "assert" too.

I'm open to consider refining the name in due course. Did you have anything in mind?

A few ideas:

constraint
enforce
require
evaluate
guarantee
check_assert
compile_constraint
const_constraint
constexpr_assert
compiler_assert <- suggested by Alejandro.

Some others I left off: verify, validate

Regards, Jonathan

>
>
>
> Beside preconditions are visible on both sides of function call even if not
> inlined, this means you do not need to rely on opimalzier to do this job
> as you put enough preconditions to make all checks local.
>

Received on 2026-03-03 09:23:49