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 :
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;
}();