Home > Article > Backend Development > How to Initialize a C Member Array with an Initializer List?
While attempting to initialize a member array with an initializer list, you encounter a compiler error: incompatible types in assignment of ‘std::initializer_list
Rather than an initializer list constructor, you can opt for a variadic template constructor:
<code class="cpp">struct Foo { int x[2]; template <typename... Ts> Foo(Ts... ts) : x{ts...} {} };</code>
With this approach, you can initialize your Foo object as follows:
<code class="cpp">Foo f1(1, 2); // OK Foo f2{1, 2}; // Also OK Foo f3(42); // OK; x[1] zero-initialized Foo f4(1, 2, 3); // Error: too many initializers</code>
If constantness is not essential, you can initialize the array within the function body after skipping initialization in the constructor:
<code class="cpp">struct Foo { int x[2]; // or std::array<int, 2> x; Foo(std::initializer_list<int> il) { std::copy(il.begin(), il.end(), x); // or std::copy(il.begin(), il.end(), x.begin()); // or x.fill(il.begin()); } }</code>
This method, however, lacks the compile-time bounds checking offered by the variadic template constructor.
The above is the detailed content of How to Initialize a C Member Array with an Initializer List?. For more information, please follow other related articles on the PHP Chinese website!