C++ Logo

std-proposals

Advanced search

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

From: Alejandro Colomar <une+cxx_std-proposals_at_[hidden]>
Date: Fri, 27 Feb 2026 15:41:53 +0100
Hi all,

I've CCed both Jonathans elsewhere where I showed an interesting use
case for this assertion. I'll show it here too.

On 2026-02-27T14:12:03+0000, Jonathan Grant via Std-Proposals wrote:
> On 22/02/2026 08:24, Jonathan Wakely wrote:
> > All the examples are trivial. Can you show it being used in larger
> > codebases? Even an example with more than one translation unit would
> > be more interesting than just 16 different main() functions. Most
> > applications consist of more than main() and one or two static
> > functions in the same translation unit.
>
> That's a good point. I use on multi file projects. But as you say,
> it's more interesting evaluating an idea if it works across different
> files. I'll add that to my list of things to improve.
>
> There is a two file example showing how an API can be checked (forces
> change on to the calling code)
> https://github.com/jonnygrant/compile_assert/tree/main/main13
>
> I appreciate all the discussion.

I have an example for compiler_assert() which is trivial *and* very
useful at the same time.

Consider the memcpy(3) function. It's difficult to use correctly.

If you have a couple of arrays:

 int64_t a[4];
 int32_t b[2 * 4];

and we want to copy one into the other:

 memcpy(a, b, sizeof(a));

We know this works, because we see the arrays obviously have the same
size. However, memcpy(3) itself doesn't verify this, and it would be
easy to make a mistake. What if one of the arrays is larger than the
other? I've seen code like this:

 memcpy(a, b, MIN(sizeof(a), sizeof(b)));

But of course that's completely bogus. Imagine that the arrays really
differ in size. The copy wouldn't be meaningful at all.

An obvious safe wrapper would verify that both arrays have the same
size, and then use that size for the copy. See the following wrapper
(valid in ISO C2y):

 // sizeof_a - sizeof array
 #define sizeof_a(a) (_Countof(a) * sizeof((a)[0]))

 // memcpy_a - memory copy array
 #define memcpy_a(dst, src) \
 ( \
  static_assert(sizeof_a(dst) == sizeof_a(src)), \
  memcpy(dst, src, sizeof_a(dst)) \
 )

which could be used as

 memcpy_a(a, b);

This would fail to compile if the arrays have different size (or if they
are not arrays).

In C, we have VLAs, and we may want to also copy these arrays:

 void f(int n)
 {
  if (n > 200)
   exit(1);

  int64_t a[n];
  int32_t b[2 * n];

  ...

  memcpy_a(a, b);

  ...
 }

static_assert(3) would reject such input. However, compiler_assert()
would be able to work, as it would determine that while n is unknown,
the sizes of both arrays are known to be the same (after optimizations).


Have a lovely day!
Alex

-- 
<https://www.alejandro-colomar.es>

Received on 2026-02-27 14:42:05