Home >Backend Development >C++ >How to Elegantly Initialize `std::array` with Non-Default Constructible Types in C ?
Elegant Initialization of std::array
In the realm of C , std::array
Consider the following code snippet:
<code class="cpp">template<typename T, int N> void f(T value) { std::array<T, N> items = {value, value, value, value, value}; }</code>
While straightforward, manually repeating the value becomes tedious as N increases. To address this issue, a more elegant approach is to leverage C 17's structured bindings and variadic templates.
Utilizing Sequence Generators and the Repeat Function
The key to this elegant solution lies in generating a sequence-type seq<0,1,2,3,...N-1> using the genseq_t<> generator. With this sequence-type, we can define a repeat function that takes a value and the generated sequence as parameters and returns an std::array
Example Implementation
<code class="cpp">template<typename T, int N> void f(T value) { // genseq_t<N> represents seq<0,1,...N-1> std::array<T, N> items = repeat(value, genseq_t<N>{}); }</code>
Pattern Details
This technique allows for concise and elegant initialization of std::array
The above is the detailed content of How to Elegantly Initialize `std::array` with Non-Default Constructible Types in C ?. For more information, please follow other related articles on the PHP Chinese website!