Home  >  Article  >  Backend Development  >  How to Initialize `std::array` for Non-Default Constructible Types Elegantly?

How to Initialize `std::array` for Non-Default Constructible Types Elegantly?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 09:53:27525browse

How to Initialize `std::array` for Non-Default Constructible Types Elegantly?

Elegant Initialization of std::array for Non-Default Constructible Types

In this context, initializing an std::array can be a challenge when the contained type (T) lacks a default constructor. A common solution involves manually repeating the value to fill the array, a tedious and error-prone process for large n values.

Fortunately, a more elegant approach exists using a combination of sequence types and a custom repeat function. Consider the following code:

<code class="cpp">template<typename T, int N>
void f(T value)
{
    // Generate a sequence of numbers: 0, 1, ..., N-1
    using genseq_t = genseq_t<N>;
    std::array<T, N> items = repeat(value, genseq_t{});
}</code>

The genseq_t type represents a sequence of numbers from 0 to N-1, and the repeat function takes a value and a sequence, returning an array filled with that value.

The repeat function's implementation involves unpacking the sequence and repeating the value for each element using a concise syntax:

<code class="cpp">template<typename T, int...N>
auto repeat(T value, seq<N...>) -> std::array<T, sizeof...(N)>
{
    // Unpack N, repeating 'value' sizeof...(N) times
    return {(N, value)...};
}</code>

The genseq_t type is defined recursively using a push_back operation to create a sequence:

<code class="cpp">template<int N>
struct genseq : genseq<N - 1>::type::template push_back<N - 1> {};</code>

The custom sequence and repeat function provide a flexible and elegant solution for initializing std::array with non-default constructible types.

The above is the detailed content of How to Initialize `std::array` for Non-Default Constructible Types Elegantly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn