Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize member array at compile time

Is it possible to initialize the idx value of the array_object at compile time such that member_array[0].idx = 0; member_array[1].idx = 1;member_array[array_size-1].idx = array_size-1. The value member of every array_object should be initialized with an empty string literal.

struct my_class {
    struct array_object {
        int idx;
        std::string value{};
    };
    static constexpr size_t array_size = /* some compile time constant*/;

    std::array<array_object, array_size> member_array = /* default initialize where idx of each array_object is +1 of the preceeding array_object
                                                        and the first array_object idx is 0 ; array_object value always initialized to empty string*/;
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could use a pack of indices to initialize the array:

std::array<array_object, array_size> member_array =
    []<std::size_t... I>(std::index_sequence<I...>) {
        return std::array<array_object, array_size>{{{I, {}}...}};
//                                                    ^  ^^
//                                                   idx value
    }(std::make_index_sequence<array_size>{});

I here holds the indices [0, array_size) which is then expanded to form:

{0, {}}, {1, {}}, {2, {}}, ..., {array_size-1, {}}

Or use a loop:

std::array<array_object, array_size> member_array = []{
    std::array<array_object, array_size> rv;
    for(size_t i = 0; i < array_size; ++i) rv[i].idx = i;
    return rv;
}();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading