I have a template class that contains a single member array of compile-time constant length. I want this array to be constant, but initializing it based on constructor-provided input is proving difficult:
struct Input {
int value;
};
template<size_t Size>
struct Foo {
int const myVals[Size];
Foo(std::array<Input, Size> const &in)
: myVals{ in[0].value, in[1].value, /* How many times? */ } {
}
}
Since I don't know the size of the array, I don't know how many values with which to initialize myVals. The following code works, but I question whether it is the best approach:
template<size_t Size>
struct Foo {
std::array<int, Size> const myVals;
Foo(std::array<Input, Size> const &in)
: myVals{ toIntArray(in) } {
}
private:
static std::array<int, Size> toIntArray(std::array<Input, Size> const &in) {
std::array<int, Size> result;
for (size_t i{ 0 }; i < Size; ++i) {
result[i] = in[i].value;
}
return result;
}
}
Is there a more succinct, or generally more accepted way to populate the values of a constant member array?
myValshas typeint[], one when initializing withmyVals{in}, and finally, one when initializing withmyVals(in)). Which compiler are you using where anstd::arraycan be initialized by a type with different template parameters?