vendredi 30 juin 2023

Template queue with pre defined size

I want something like this: Queue<type, size> my_queue;. Here the typeis whatever I want. It can be an array, a structure or something else. Size is the maximum allowed elements that my_queue object can contain. From this thread I understand that I must have a wrapper class that allows me to set a size value and access to the actual queue through the wrapper class. But I also must be able to instantiate a Queue object with different types.

So I thought I can solve my problem by using templates. My only constraint is limiting the Queue size in order to limit the dynamically allocated memory by the std::queue. I thought I can inherit from the std::queue and simply create a class like this:

template<typename T>
class Queue final : public std::queue<T> {
public:
    Queue(T type, uint32_t size) : size_(size) { };

    virtual ~Queue() = default;

    bool push(T new_element) {
        if(this->size() < size_) {
            this->push(new_element);
            return 1;
        }
        return 0;
    }
    ;

private:
    const uint32_t size_ = 0;
};

This is compiling. But I know it is not correct. I do not know how can I do it. Also when I want to create an instance of Queue like Queue<uint8_t[5], 5> my_queue; it does not compile.

Aucun commentaire:

Enregistrer un commentaire