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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 17:50:02798browse

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

How to Initialize a Member Array with an Initializer List

In C 0x, you can initialize a member array with an initializer list as follows:

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

However, this code will not compile in g 4.6, resulting in the error:

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

To resolve this issue, you can use a variadic template constructor instead:

<code class="cpp">struct Foo {
    int x[2];
    template <typename... T>
    Foo(T... ts) : x{ts...} {}
};

int main() {
    Foo f1(1, 2); // OK
}</code>

Alternatively, you can skip initialization and fill the array in the function body if you can live without constness:

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

While this latter method allows you to initialize the array with an initializer list, it does not provide compile-time bounds checking like the variadic template constructor approach.

The above is the detailed content of How to Initialize a Member Array with an Initializer List in C 0x?. 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