Initializing Non-Default Constructible std::array Without Repetition
In C , initializing an std::array of non-default constructible elements can be a challenge. Standard initialization methods becomeumbersome when n, the array size, is large or a template parameter.
Solution:
An elegant solution leverages a combination of iterators and templates. Here's how it works:
We define two helper utilities:
Using these utilities, we can initialize the std::array in the template function f as follows:
<code class="cpp">template<typename T, int N> void f(T value) { std::array<T, N> items = repeat(value, genseq_t<N>{}); }</code>
Implementation Details:
Example:
Consider an initialization with value as an integer and n as a template parameter:
<code class="cpp">void f(int value) { std::array<T, 5> items = repeat(value, genseq_t<5>{}); }</code>
Here, items will be initialized with the value repeated five times: {value, value, value, value, value}.
Advantages:
This approach is more concise, especially when n is large. It also eliminates the need for manually repeating the value.
The above is the detailed content of How to Initialize a Non-Default Constructible `std::array` Without Repetition in C ?. For more information, please follow other related articles on the PHP Chinese website!