Is there some way to create an array in C++ where we don't know the type, but we do know it's size and alignmnent requirements?
Let's say we have a template:
template<typename T>
T* create_array(size_t numElements) { return new T[numElements]; }
This works because each element T has known size and alignment, which is known at compile-time. But I'm looking for something where we can delegate the creation for later by simply extracting size and align and passing them on. This is the interface that I seek:
// my_header.hpp
// "internal" helper function, implementation in source file!
void* _create_array(size_t s, size_t a, size_t n);
template<typename T>
T* create_array(size_t numElements) {
return (T*)_create_array(sizeof(T), alignof(T), numElements);
}
Can we implement this in a source file?:
#include "my_header.hpp"
void* _create_array(size_t s, size_t a, size_t n) {
// ... ?
}
Requirements:
- Each array element must have the correct alignment.
- The total array size must be equal to s*n, and be aligned to a.
- Type safety is assumed to be managed by the templated interface.
- Indexing into the array should use correct size and align offsets.
I'm using C++20, so newer features may also be considered. In advance, thank you!
std::aligned_storage::typeas the element type, and thenplacement-newyour actual objects onto those array elements afterwards as needed. Except that the size and alignment values foraligned_storageneed to be template parameters, not runtime function parameter. Hmm...std::vector...aligned_alloc, no compile-time type required.<memory_resource>? It's the library spec and support for polymorphic allocators. You might be able to draw up some inspiration there.