I'm trying to implement std::lcm and I need to static_assert
that the arguments or result are within bounds as required by the standard:
The behavior is undefined if |m|, |n|, or the least common multiple of |m| and |n| is not representable as a value of type std::common_type_t<M, N>.
Simplified the problem is this: Say I have the following code:
constexpr void foo(int x) noexcept {
if consteval {
static_assert(x == 0, "x must be 0");
}
}
Compiling a c++23 gives:
<source>: In function 'costexpr void foo(int) noexcept':
<source>:3:25: error: non-constant condition for static assertion
3 | static_assert(x == 0, "x must be 0");
| ~~^~~~
<source>:3:25: error: 'x' is not a constant expression
How do I static_assert that x == 0? Or something equivalent that shows the message on error.
Note: This is not a duplicate of Will consteval allow using static_assert on function arguments? as noexcept can't throw.
This is not a duplicate of static_assert compile-time argument check with C++20 concept because the use case (implementing std::lcm) does not allow template arguments.
This is not a duplicate of How to tell static_assert that constexpr function arguments are const?, same reason.