Home > Article > Backend Development > How to Initialize `std::array` for Non-Default Constructible Types Elegantly?
Elegant Initialization of std::array
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
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
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!