First of all, your requirements are still not entirely clear. I assume that you want "built-in storage" for the container; therefore, for example, in a "polymorphic" vector , all elements will be contiguous in memory (provided that only for proper alignment).
Now this is possible if you are ready to provide an exhaustive list of all the types that you intend to enter into the container at compile time. The simplest implementation would be to use the union of all possible types as the type of the base array, which would ensure sufficient size and proper alignment and the same O (1) access by index due to some space spent on elements of smaller types. I can go with this in more detail if you want.
If the list of types is known in advance, or if you do not want overhead, then you will have to maintain a separate pointer to pointers (or offsets from the beginning of the backup storage) to the elements, so that you can make O (1) access. Also, given alignment problems, I'm not sure if you can even do this in fully portable C ++ 03, although you definitely can in C ++ 0x.
Pavel minaev
source share