Using the C++11 std::array with explicit template parameters is problematic because overshooting the size will fill the memory with default constructed types.
Credits to MarcoFalke.
Concept ACK
86 | @@ -87,4 +87,9 @@ template <typename T1, size_t PREFIX_LEN> 87 | std::equal(std::begin(prefix), std::end(prefix), std::begin(obj)); 88 | } 89 | 90 | +/** 91 | + * User-defined literal for byte constants. 92 | + */ 93 | +constexpr uint8_t operator ""_u8(unsigned long long byte) { return byte; }
Maybe we should add some overflow assert here? it would be nice if 256_u8 won't compile.
the downside is that this function might be used outside of constexpr, but that's very unlikely
ie assert(byte <= std::numeric_limits<uint8_t>::max());
Maybe we should add some overflow assert here? it would be nice if
256_u8won't compile.
Agree...
ie
assert(byte <= std::numeric_limits<uint8_t>::max());
... but this won't work, unfortunately.
Why not? https://godbolt.org/z/hTjch7
It is not a compile-time error.
You're right, idk how I didn't realized that
You can use runtime asserts in constexpr functions. It just means invocations that would trigger that revert to being runtime evaluated. If the result is assigned to a constexpr variable, it'll error at compile time.
Why does c++ not allow constexpr params, so that a static_assert could be used here?
:man_shrugging:
I'd probably prefer std::make_array to be backported. https://en.cppreference.com/w/cpp/experimental/make_array
This would allow to write MakeArray<uint8_t>(1,2,3)
std::to_array from C++20 ?
Updated 1f16514614d37edd6e916e0aca731d445101f8f7 -> b6fb4fa999b927dce07bce239532b0f07bd393a2 (pr20571.01 -> pr20571.02, diff):
Maybe we should add some overflow assert here? it would be nice if
256_u8won't compile.
To make compiler proceed checking, all of the std::array definitions must be specified with constexpr.
Closing as this solution seems not future-proof.