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?
I'm working with C++11.
Note that this example is a gross simplification. The line arr[i] = { i, i%2==0 }; would be replaced by a function that parses incoming network data. The actual array is way bigger and the struct is also more complicated. None of the data that will populate the struct will be known at compile time, only the layout.
std::array<S,16> createAlternatingOnesZeros().return {vec[0], vec[1], ..., you can create that withBOOST_PP_REPEAT: boost.org/doc/libs/1_77_0/libs/preprocessor/doc/ref/repeat.htmlconstdata members is typically an anti-pattern and e.g. the C++ Core Guidelines have a rule against it. It prohibit moves and adds complexity to clients of the type, such as highlighted above. It seems what you are after is logical constness, which can be implemented using a class type instead, with read-only access to its non-const data members.privateinstead ofconst(or work with aconst Sinstead).