I have a data structure defined and initialized similar to the following:
#include <vector>
#include <array>
struct SomeStruct {
std::vector<int> vec;
};
int main() {
std::array<SomeStruct, 2> arr {
SomeStruct {
.vec = {
1, 2
}
},
SomeStruct {
.vec = {
3, 4, 5
}
}
};
}
This compiles correctly, but since the entire structure is known at compile time, I tried to make it a constexpr
.
Simply declaring arr
as constexpr
in the previous example results in an error:
main.cpp: In function ‘int main()’:
main.cpp:20:5: error: the type ‘const std::array’ of constexpr variable ‘arr’ is not literal
};
^
In file included from main.cpp:2:0:
/usr/include/c++/7/array:94:12: note: ‘std::array’ is not literal because:
struct array
^~~~~
/usr/include/c++/7/array:94:12: note: ‘std::array’ has a non-trivial destructor
I'm guessing this is because std::vector
does not have a constexpr
constructor/destructor.
I then tried using an std::array
with a template on the containing struct:
#include <array>
template <int N>
struct SomeStruct {
std::array<int, N> vec;
};
int main() {
constexpr std::array<SomeStruct, 2> arr {
SomeStruct<2> {
.vec = {
1, 2
}
},
SomeStruct<3> {
.vec = {
3, 4, 5
}
}
};
}
This results in an error too:
main.cpp: In function ‘int main()’:
main.cpp:10:39: error: type/value mismatch at argument 1 in template parameter list for ‘template struct std::array’
constexpr std::array<SomeStruct, 2> arr {
^
main.cpp:10:39: note: expected a type, got ‘SomeStruct’
main.cpp:10:41: error: scalar object ‘arr’ requires one element in initializer
constexpr std::array<SomeStruct, 2> arr {
^~~
But I cannot give SomeStruct the template parameter because the sizes can differ.
What is the best way to define a constexpr
data structure like this?