mercredi 2 novembre 2022

How do I create an std::array of immutable structs? I.e. structs with only const values

Say I have struct S:

struct S {
const int i;
const bool b;
}

And I want to create an (non-const) array of this struct like so:

std::array<S, 16> arr;
for(int i = 0; i<arr.size(); i++)
    arr[i] = { i, i%2==0 };

Then the compiler will complain that I didn't initialize the a const variable when I initialized the array.

I tried doing it with a vector as an intermediary. But int the function I'm writing I have to pass the original array in another struct, and return that other struct.

struct OtherStruct {
    const std::array<S,16> sArray;
};

OtherStruct f() {
    std::vector<S> vec(16);
    for(int i = 0; i<16; i++)
        vec.push_back({ i, i%2==0 });
    return { vec.data() };
}

But that didn't work either. I hoped that passing the pointer to the vector data would be cast into a C-style array, from which an std::array could be made. What is the cleanest way to fix this?

Oh I'm working with C++11

Aucun commentaire:

Enregistrer un commentaire