Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-04 17:50:02
Original
797 people have browsed it

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

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

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

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

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!

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!