for something I'm building I need to be able to store runtime created structs in an array, I also want these structs to be stored contiguously in memory. Is there a way to store a sequence of objects in an array, without knowing what objects they will be at compile time? I will know every possible object that could be used and their sizes. Basically when I define one of these arrays I will create a template of exactly what objects will be stored and in what order and after that it will not change for the lifetime of the array, meaning that at runtime the stride and positions of objects will be known. Could this be done by allocating something like a std::byte array and then accessing/initializing the variables by casing their memory positions to the desired type using a pointer? I know that it's not the cleanest solution but could it work?
Clarification: This would be used for ECS components defined by a custom scripting system at runtime, so contiguous memory and dynamic allocation is a must, I realize that I'm going to need to create class to handle this and it's going to be advanced, that's the fun of it.
So I think I found an answer:
std::vector<std::byte> bytes;
void addFloat(float value)
{
size_t index = bytes.size();
bytes.resize(bytes.size() + sizeof(float), std::byte(0));
*(float*)(&bytes[index]) = value;
}
float readFloat(size_t index) const
{
return *(float*)(&bytes[index]);
}
This can read and write floats (tested) from the vector, and I'm assuming it will work for any value type I make a function for. So now all I need to do is write a class that handles multiple value types. When the class is created I'll calculate the the size of the virtual float and store that, then I can look up a float by index using that value. Then to retrieve a component of that struct value I'll have another list that stores the offset of each variable from the 0 index of the struct. So index + offset[variable index] = index of variable, then I can cast that index to the correct type and there's my value.
Edit: See comments bellow for possible improvements.