Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class Method Specialization

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>(); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading