Currently using g -11.3.0, C 20.
I'm trying to make this class that accepts two parameters at construction: a void pointer that points to a pre-allocated block of memory, and the size of the memory block. The class then iterates through the data block with calls to the next()
method, which returns a reference of the next available slot in the data block, enclosed in the specified type T
.
class DataArrayIterator
{
private:
void* data;
size_t maxSize;
size_t size;
public:
template<typename T>
T& next<T>()
{
assert(sizeof(T) size <= maxSize);
size_t offset = size;
size = sizeof(T);
return *((T*)(static_cast<char*>(data) offset));
}
DataArrayIterator(void* data, size_t maxSize)
: data{data}, maxSize{maxSize}, size{0}
{
}
};
Compiling the code gives me the error non-class, non-variable partial specialization ‘next<T>’ is not allowed
. Is there anything I could do to mimic the same functionality as closely as possible? Or are there more suitable alternatives?
CodePudding user response:
You don't need any partial specialisation in this case, just introduce a function template:
template<typename T>
T& next() {
... // implementation goes here
}
And instantiate the function when needed:
auto i = 8;
// val is an int reference with value of 8
auto& val = DataArrayIterator{ &i, sizeof(i) }.next<int>();