Home > Backend Development > C++ > body text

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

Mary-Kate Olsen
Release: 2024-11-04 05:41:02
Original
737 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!