I'm trying to write a helper function that converts two arrays to an array of pairs, which is used to initialize some static data stored in my program.
So far, I've written a constexpr function that accepts two arrays of the same length, and returns a std::array
by value, which is then used to initialize an array.
inline std::array<param_t, N> transpose(int const (&mg)[N], int const (&eg)[N]) {
std::array<param_t, N> ret{};
for(size_t i = 0; i < N; i++) {
ret[i] = {mg[i], eg[i]};
}
return ret;
}
struct some_params {
param_t mat[5] = transpose({92, 367, 444, 583, 1342}, {88, 370, 394, 646, 1233});
}
This generates a compiler error: Array initializer must be an initializer list
. I'm not sure how I can return a std::initializer_list
, given that it doesn't have a suitable constructor and is designed as a temporary. For various reasons, I can't change the type of mat to std::array
.
How can I initialize an array like this from a function?
I'm not sure how I can return a std::initializer_list,
A non-empty std::initializer_list
can only be constructed using a brace-init-list. You cannot build up a std::initializer_list
from an empty object.
For your specific use case, you may use:
std::array<param_t, 5> mat = transpose({92, 367, 444, 583, 1342}, {88, 370, 394, 646, 1233});