Home > Backend Development > C++ > How to Initialize Member Arrays with Initializer Lists in C 0x?

How to Initialize Member Arrays with Initializer Lists in C 0x?

Mary-Kate Olsen
Release: 2024-11-02 17:25:29
Original
843 people have browsed it

How to Initialize Member Arrays with Initializer Lists in C  0x?

Initializing Member Arrays with Initializer Lists

In C 0x, you may encounter the error "incompatible types in assignment" when attempting to initialize a member array with an initializer list.

To resolve this, consider using a variadic template constructor instead:

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

int main() {
    // Usage
    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
    foo f5(3.14);  // Error: narrowing conversion not allowed
    foo f6("foo"); // Error: no conversion from const char* to int
}</code>
Copy after login

If preserving the 'const' status is not essential, you could alternatively employ a function to load the array values:

<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

However, this approach relinquishes compile-time bounds checking.

The above is the detailed content of How to Initialize Member Arrays with Initializer Lists 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