Search code examples
c++arraysc++17variadic-templatesplacement-new

Initialize array using variadic template list and placement new


I am trying to implement the following function:

template<typename T, typename... ARGUMENTS>
std::unique_ptr<T[], HeapDeleter<T[]>> allocate_array( ARGUMENTS&&... arguments ) {
HeapAllocator<T> allocator;

/* Allocate array which size is equal to number of arguments given */
T* ptr = allocator.template allocate<sizeof...(ARGUMENTS)>();
if( ptr != nullptr ) {
/* TODO: There comes the magic... */
}

First step is to allocate memory for the array using allocate<>() call. This should already be clear but what I am about to add is to call the constructor for every array element within the allocated memory using the placement new. There exactly I would like to kindly ask for help...

Basically for a single element I can write:

::new( static_cast<void*>( ptr ) T( /* One argument from arguments given */ );

The idea is to initialize n-th element with n-th argument within the arguments list on ptr+n address, ideally using move constructor to avoid unnecessary copies.

I hope you got the idea... Many thanks in advance for help!

Martin


Solution

  • A chance to utilise fold expressions. Yay :)

    You can use comma operator to repeat operation and a counter for increasing index:

    std::ptrdiff_t i = 0;
    (::new(ptr + i++) T(arguments), ...);