I like to have some sort of static (compile-time) check, if a type is initialised with a constant.
Below is a test code. The type C is just a test to see if/when constant-evaluation is triggered.
The type D is more to be a real example of what I want to do:
Runtime: if D is initialized with the wrong value, the value might be clamped somewhat or a runtime-assertion should trigger
Compiletime: if D is initialized with the wrong value, the compilation should fail.
I can't find a solution for that.
The code:
#include <cassert>
#include <type_traits>
inline void constant_assert() {}
struct C {
constexpr C() {
if (std::is_constant_evaluated()) {
constant_assert();
}
}
};
struct D {
constexpr D(const char v) {
if (std::is_constant_evaluated()) {
//static_assert(v < 10); // not callable
if (v >= 10) {
constant_assert();
}
}
else {
assert(v < 10);
}
}
};
int main() {
C t0; // does not trigger the check
// constexpr C t1; // triggers the check: ok
D d{42}; // runtime assert, but should be compiletime error!
}
The above code in CE: https://godbolt.org/z/16GTx797q