"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Initialize Member Arrays with Initializer Lists in C++0x?

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

Published on 2024-11-08
Browse:311

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:

struct foo {
    int x[2];
    template 
    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
}

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

struct foo {
    int x[2];
    foo(std::initializer_list il) {
        std::copy(il.begin(), il.end(), x);
    }
};

However, this approach relinquishes compile-time bounds checking.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3