I have to initialize a std::array<my_vector, N>, my_vector being a std::vector with a custom allocator. The way I did it is:
- Allocated
Nmemory pools - Created a
std::arrayofallocator, that each have their memory pool - Created a
std::arrayofstd::vector, that each have their allocator.
The simplified code looks like this:
std::array<std::array<char, POOL_SIZE>, N> memory_pools;
std::array<allocator<POOL_SIZE>, N> allocators{
std::get<0>(memory_pools),
std::get<1>(memory_pools),
std::get<2>(memory_pools),
//...
std::get<N-1>(memory_pools),
};
using my_vector = std::vector<my_class, my_allocator>;
std::array<my_vector, N> vectors{
my_vector{std::get<0>(allocators)},
my_vector{std::get<1>(allocators)},
my_vector{std::get<2>(allocators)},
//...
my_vector{std::get<N-1>(allocators)},
}
This works, however, this is quite verbose, given that my constant N is over 100, and writing all this by hand produces bloated code, and when I change N, I have to write this whole section again.
Question: Is there any way to make the compiler write the initialisation for me ?
What I want to do is
std::array<allocator<POOL_SIZE>, N> allocators =
make_array_from_pool<POOL_SIZE, N>(memory_pools);
std::array<my_vector, N> vectors =
make_array_from_allocators<N>(allocators);
I've already tried to do some recursive templated function, inside a nested class, but I'm confronted with conversion error.
This is roughly what I was trying:
template<size_t POOL_SIZE, size_t N, size_t ORDER>
class ArrayMaker{
static std::array<allocator<POOL_SIZE>, ORDER> from_pool(
std::array<std::array<char, POOL_SIZE>, N>
memory_pool
){
return {
ArrayMaker<POOL_SIZE, N, ORDER-1>::from_pool(memory_pool),
std::get<ORDER-1>(memory_pool)
};
}
};
template<size_t POOL_SIZE, size_t N>
class ArrayMaker<POOL_SIZE, N, 1>{
static std::array<allocator<POOL_SIZE>, 1> from_pool(
std::array<std::array<char, POOL_SIZE>, N>
memory_pool
){
return {std::get<0>(memory_pool)};
}
};
template<size_t POOL_SIZE, size_t N>
static std::array<allocator<POOL_SIZE>, N> make_array_from_pool(
std::array<std::array<char, POOL_SIZE>, N>
memory_pool
){
return ArrayMaker<POOL_SIZE,N, N>::from_pool(memory_pool);
}
The error I get is could not convert ... from '<brace-enclosed initializer list>' to 'std::array<allocator<POOL_SIZE>, 2>'
It's my understanding that it is because std::array only supports aggregate initialisation.