Home  >  Article  >  Backend Development  >  How to Initialize Member Arrays in C 0x Constructors: Why Does Using `std::initializer_list` Fail and How to Resolve It?

How to Initialize Member Arrays in C 0x Constructors: Why Does Using `std::initializer_list` Fail and How to Resolve It?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 17:32:29452browse

How to Initialize Member Arrays in C  0x Constructors: Why Does Using `std::initializer_list` Fail and How to Resolve It?

Initializer Lists and Member Arrays in C 0x

In the early stages of learning C 0x, it's common to encounter syntax errors when experimenting with new features. Specifically, this issue arises when attempting to initialize a member array within a constructor using an initializer list.

Consider the following code:

<code class="cpp">struct Foo
{
    int const data[2];

    Foo(std::initializer_list<int const>& ini)
    : data(ini)
    {}
};

Foo f = {1,3};</code>

Upon compilation, this code triggers the following error:

incompatible types in assignment of ‘std::initializer_list<const int>&’ to ‘const int [2]’

To resolve this error, the approach recommended in the provided answer involves employing a variadic template constructor instead of an initializer list constructor. Using this method ensures type compatibility and allows for flexible initialization of member arrays:

<code class="cpp">struct foo {
    int x[2];
    template <typename... T>
    foo(T... ts) : x{ts...} {} // curly braces syntax for initializer list
};

int main() {
    foo f1(1, 2);   // compiles successfully
    foo f2{1, 2};   // also compiles
    foo f3(42);    // x[1] is zero-initialized
}</code>

Alternatively, if maintaining constness is not crucial, you can opt for a method that involves populating the array within the constructor body:

<code class="cpp">struct foo {
    int x[2]; 
    foo(std::initializer_list<int> il) {
       std::copy(il.begin(), il.end(), x);
    }
};</code>

While this approach may be viable, it sacrifices the compile-time bounds checking provided by the variadic template constructor.

The above is the detailed content of How to Initialize Member Arrays in C 0x Constructors: Why Does Using `std::initializer_list` Fail and How to Resolve It?. 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