I'd like to can create a template function, which can initialize (with placement new) an array, where for each element, a lambda is called to initialize it.
template <typename OBJECT, typename LAMBDA>
void initialize(void *storage, int size, LAMBDA lambda) {
for (int i=0; i<size; i++) {
lambda(static_cast<char*>(storage)+i*sizeof(OBJECT), i);
}
}
Where an actual lambda could be this (for example, an integer array, where each element get initialized to its index):
[](void *storage, int index){ new(storage) int(index); }
And this works. However, as I see, it doesn't create an actual array, because I didn't used a placement-new-array, but separate placement-new calls for each element, even though the memory layout should be the same. Am I right? Can I refer to this memory as an array? If not, can this functionality be achieved somehow?
(Basically, this functionality is the same, if std::vector
had a array-generator push_array_back
function, which has a size
and lambda
parameters. And it would push_back
an elements of size
, initialized to the value lambda
gives)