How to use .size()
method of some initialized vector in a static_assert
expression?
Say I have a vector of bytes, it has to have a length of 8, I want to convert it to uint64_t
using big endian, but only if it has a length of 8, if its length is not 8, I want an exception to be thrown.
The following code works:
#include <vector>
using std::vector;
using bytes = vector<uint8_t>;
static inline uint64_t UInt64BE(const bytes& arr) {
if (arr.size() != 8)
throw;
return (uint64_t(arr[0]) << 56) | (uint64_t(arr[1]) << 48) |
(uint64_t(arr[2]) << 40) | (uint64_t(arr[3]) << 32) |
(uint64_t(arr[4]) << 24) | (uint64_t(arr[5]) << 16) |
(uint64_t(arr[6]) << 8) | arr[7];
}
But the following doesn’t:
static_assert(arr.size() == 8);
The error is: “expression must have constant value”.
How can I use static_assert
to do this?
Note I am using Visual Studio 2022 17.9.7 on Windows 10, C++20 standard, and #include <assert>
fails with cannot open source file "assert"
.