Skip to content

Instantly share code, notes, and snippets.

@fredemmott
Last active June 30, 2024 18:15
Show Gist options
  • Save fredemmott/912f3a46c7c1261c48f042ee02f3742e to your computer and use it in GitHub Desktop.
Save fredemmott/912f3a46c7c1261c48f042ee02f3742e to your computer and use it in GitHub Desktop.
#include <array>
#include <tuple>
#include <cstddef> // for size_t
// concatenate multiple arrays - requires C++20
//
// The usual approach is to default-construct `std::array<T, Na + Nb>`, then
// overwrite the elements, e.g. with `std::copy()` or loops.
//
// The problem with that is it requires that `T` is default-constructable;
// this implementation does not have that requirement.
template <class T, size_t Na, size_t Nb>
constexpr auto array_cat(
const std::array<T, Na>& a,
const std::array<T, Nb>& b,
auto&&... rest) {
if constexpr (sizeof...(rest) == 0) {
return std::apply([](auto&&... elements) {
return std::array { std::forward<decltype(elements)>(elements)... };
}, std::tuple_cat(a, b));
} else {
return array_cat(a, array_cat(b, std::forward<decltype(rest)>(rest)...));
}
}
constexpr std::array a { 1, 2};
constexpr std::array b { 3, 4};
constexpr std::array c { 5, 6};
static_assert(array_cat(a, b) == std::array { 1, 2, 3, 4});
static_assert(array_cat(a, b, c) == std::array { 1, 2, 3, 4, 5, 6});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment