Home  >  Article  >  Backend Development  >  How to Initialize a C Member Array with an Initializer List?

How to Initialize a C Member Array with an Initializer List?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 05:41:02739browse

How to Initialize a C   Member Array with an Initializer List?

Assignment Error When Initializing C 0x Member Array with 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’ to ‘const int [2]’.

Solution Using Variadic Template Constructor

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>

Solution Using Non-Constant Member Array and Initialization in Function Body

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!

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