How can I write an std::array concatenation function?
template <typename T, std::size_t sza, std::size_t szb>
std::array<T, sza+szb> concat (const std::array<T, sza>& aa,
const std::array<T, szb>& ab)
{
std::array<T, sza+szb> result;
std::copy(std::begin(aa), std::end(aa), std::begin(result));
std::copy(std::begin(ab), std::end(ab), std::begin(result) + sza);
return result;
}
This of course doesn't work when T is not default-constructible. How can this be fixed?
Explicit template parameter list for lambdas, as shown in n. m.'s answer, were introduced in C++20.
A C++14 solution needs an helper function:
template <typename T, std::size_t... ai, std::size_t... bi>
std::array<T, sizeof...(ai) + sizeof...(bi)>
concat_impl(std::array<T, sizeof...(ai)> const& aa,
std::array<T, sizeof...(bi)> const& ab,
std::index_sequence<ai...>, std::index_sequence<bi...>)
{
return std::array<T, sizeof...(ai) + sizeof...(bi)>{
aa[ai]..., ab[bi]...
};
};
template <typename T, std::size_t sza, std::size_t szb>
std::array<T, sza + szb> concat (std::array<T, sza> const& aa,
std::array<T, szb> const& ab)
{
return concat_impl(aa, ab,
std::make_index_sequence<sza>{},
std::make_index_sequence<szb>{});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With