Background Information
- I am consuming an API that gives access to a read-only buffer of floats (const float*)
- I need to break this up into chunks which I do by creating a
nonstd::span<const float> initialised with the pointer and the number of elements in the chunk.
- I am using the span-lite implementation of span available from
https://github.com/martinmoene/span-lite
- I then wrap this span in a simple structure (used to hold other metadata as well, removed below as it is not important here) as follows:
1 2 3 4 5 6 7 8 9
|
struct Chunk
{
explicit Chunk(nonstd::span<const float>& bytes) : bytes(bytes)
{
}
public:
nonstd::span<const float> bytes;
};
| |
I add the resulting structures to a vector, shown by the following code:
1 2 3 4 5 6 7 8 9 10 11
|
const auto chunkCount = 10;
const auto chunkSize = 1024;
const auto* buffer = externalApi.getBufferPointer();
std::vector<Chunk> chunks(chunkCount);
auto offset = 0;
for (auto index = 0; index < chunkCount; ++index, offset += chunkSize)
{
chunks.emplace_back(&buffer[offset], chunkSize);
}
| |
The above all works and I can use the chunks as expected.
Issue Description
What I want to achieve is to be able to additionally define my own chunks, so:
- Allocate the bytes
- Fill them in as desired
- Add them to the above vector of existing chunks
So the result will be a vector that contains a mix of chunks pointing to data defined by the external API and chunks pointing to data i have created. Since I am allocating the data, it will not be a span<>, but rather an array or similar. My idea is to conceptually have an interface, such as Chunk, that is then subclassed by SpanChunk and ArrayChunk, then added to the vector so that the consumer is not concerned with the actual implementation of the chunks. The interface must satisfy the following constraints:
- Be const iterable (i.e. iterate through the 'bytes' in the chunk). This is important so the chunk can be used with std::transform(), etc
- Be able to index-access the bytes (i.e. const float dataByte = chunk[36])
So far my attempts at implementing such polymorphism has been unsuccessful, though I could achieve the same in C#, Java and other languages I am more familiar with. Can someone guide me in the right direction for how to solve this situation in C++ and perhaps provide some example implementation of the subclasses if this is the right way to solve the problem.