Home > Backend Development > C++ > body text

Can initializer lists initialize const member arrays in C 0x?

Barbara Streisand
Release: 2024-11-02 16:15:29
Original
281 people have browsed it

Can initializer lists initialize const member arrays in C  0x?

Initializer Lists for Member Arrays: A C 0x Puzzle

In C 0x, the introduction of initializer lists has opened up new possibilities for initializing data members. However, a common misconception can arise when attempting to use them with arrays of const members.

Consider the following code:

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

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

int main() {
    Foo f = {1, 3};
}</code>
Copy after login

Contrary to expectations, this code will fail to compile with the error:

<code class="text">incompatible types in assignment of ‘std::initializer_list<const int>’ to ‘const int [2]’</code>
Copy after login

The issue stems from the fact that the array member data is constant, while the initializer list ini holds non-constant values. To resolve this mismatch, the compiler would need to perform a const conversion on each value in the initializer list. However, this is not permitted by the language specs.

Variadic Template Constructor to the Rescue

Instead of using an initializer list constructor, a variadic template constructor can be employed:

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

int main() {
    Foo f1(1, 2);
    Foo f2{1, 2};
}</code>
Copy after login

This constructor takes a variable number of parameters, allowing for direct initialization of the array elements. Note the use of brace-init-lists in the initialization phase {ts...}.

Non-Constant Case

If constness is not a requirement, another approach is to skip initialization in the constructor and fill the array in the function body:

<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

This method loses compile-time bounds checking but is still a viable option in certain situations.

The above is the detailed content of Can initializer lists initialize const member arrays 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!