I am looking for a convenient and efficient way to initialize a static array in a function template. For example, let's say we have a function like this:
template <size_t windowSize>
int process_signal(int currentSignal)
{
// incorrect: inits only 3 elements; want to set all values to -1
static std::array<int, windowSize> window = { -1, -1, -1 };
// do something...
}
This way I can initialize only first 3 elements with -1, but not all of them.
The best solution I've come up so far is using constexpr
function for compile-time initialization:
template <size_t sz, int value>
constexpr std::array<int, sz> init_array()
{
std::array<int, sz> arr{};
//arr.fill(-1); // will be constexpr since C++20
// operator [] is constexpr in C++17
for (int i = 0; i < sz; ++i)
arr[i] = value;
return arr;
}
template <size_t windowSize>
int process_signal(int currentSignal)
{
// works fine, but extra variable needed
constexpr static std::array<int, windowSize> init_value = init_array<windowSize, -1>();
static std::array<int, windowSize> window = init_value;
// window will be updated...
}
This way I can initialize the array once at compile-time. However, it requires an additional constexpr
variable (in my case init_value
) to bind the result of init_array()
function. And if I try the same without it, init_array()
is called as a normal function (so initialization is no longer compile-time):
template <size_t windowSize>
int process_signal(int currentSignal)
{
// no longer compile-time in MSVC2019
static std::array<int, windowSize> window = init_array<windowSize, -1>();
// window will be updated...
}
Is it possible to do the same without extra constexpr
variable? Or, maybe, it is just specific to my compiler (MSVC 2019)?