I have a list class in which the size variable is a const
member. This is helpful to me because it enforces the requirement that the size of the list may vary from run to run, but can't vary within an individual run.
I would like to create a collection of these lists. The number of lists in the collection is a template variable, so I'd like to use a std::array
... i.e., I'd like an array of lists, where the size of the array is a template parameter and the size of each list is a const
specified at construction
Unfortunately:
- The const-size list has no default constructor (its size needs to be specified!), so I need to supply a constructor argument to each element of the list. I can't just create the array and then set the elements
- Because my list size is a template variable, I can't use a standard initializer list - the number elements required varies
I recognize that there are alternatives:
- I could use a
std::vector
and justpush_back
the elements one by one until the size of the vector is equal to my template parameter, but this seems inelegant because it wouldn't naturally enforce the condition that the resulting vector's size shouldn't be changed after it's fully populated. - I could flip the index ordering, and have a const-sized list of
std::arrays
. This doesn't fit nicely with the rest of my code, however; I would like to be able to pass an individual const-sized list from the array to client code - I could create a default constructor for the const sized list class, create the array, and then use placement new to replace the array elements one-by-one. This seems like it could have some bad side-effects (what does const-sized list's default constructor do? What if it's called accidentally elsewhere? What happens when my successor has no idea what I've done?)
Since none of these are completely ideal, I'm thinking that it would be great if there were an array constructor (or helper function) which would take, as arguments:
- The number of elements in the array of T
- A single T object
...and return a std::array<T>
where each T
has been copy-constructed from argument 2.
Does such a thing exist?
Aucun commentaire:
Enregistrer un commentaire