Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piecewise initialisation of std::array

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?

like image 645
n. 1.8e9-where's-my-share m. Avatar asked Jan 22 '26 17:01

n. 1.8e9-where's-my-share m.


1 Answers

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>{});
}
like image 73
Bob__ Avatar answered Jan 25 '26 06:01

Bob__



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!