I am trying to create a std::array<uint8_t,N> from a std::span<uint8_t,N> but I cannot find a way to do so without memcpy, std::copy, or std::ranges::copy which don't protect me against wrong specification of destination array size.
#include <algorithm>
#include <array>
#include <iostream>
#include <span>
int main(int argc, char **argv) {
constexpr size_t N = 10;
std::array<uint8_t, N> original;
std::span span(original); // of type std::span<uint8,N>
std::array copy1(span); // does not work
std::array<uint8_t, N> copy2(span); // does not work
std::array<uint8_t, N> copy3(begin(span), end(span)); // does not work
// ugly stuff that works, but does not protect me if I specify wrong array size
constexpr size_t M{N - 1}; //oops, leads to array overflow
std::array<uint8_t, M> copy4;
std::copy(begin(span), end(span), copy4.begin());
std::ranges::copy(span, copy4.begin());
return 0;
}
What is the idiomatic way to do this in modern C++?
To expand on @Jarod42's answer, we can make a few improvements:
If you wanted to further reduce the assembly size, you could use the following condition instead:
If you fear that there is overhead from
std::ranges::copyover initialization, you can usestd::is_trivially_default_constructible_v<T>, possibly withstd::ranges::uninitialized_copy, which should mitigate this.