开发者

Fixed size list

开发者 https://www.devze.com 2023-03-02 16:31 出处:网络
I\'m writing a FixedSizeList class using a fixed array. I\'ve a problem with the fixed size template parameter, and I\'m try to understand if my solution is correct and even how I can solve my problem

I'm writing a FixedSizeList class using a fixed array. I've a problem with the fixed size template parameter, and I'm try to understand if my solution is correct and even how I can solve my problem.

Basically, this is the skeleton of my class:

#pragma once

template <typename T, unsigned int N>
class SListFixed
{
public:
    SListFixed();

private:
    template <typename T>
    struct Node
    {
        Node(T value)
            :element(value), nextElement(0)
        {
        }

        T element;
        int nextElement;
    };

    Node m_data[N];
    int m_head;
    int m_tail;
    size_t m_elementCounter;
};

The first question is on the correctness of this structure. Then I want to understand why this code 开发者_Go百科doesn't compile. Should I make m_data a pointer and allocate that on the stack?

Thanks.


To get this to compile, change

Node m_data[N];

to

Node<T> m_data[N];

Because Node, after all, is a template class.

That said, simply doing what Oli said and removing the template <typename T> from the definition of Node will also work because T is known from the FixedSizeList instantiation. I would recommend doing that because the type of Node couldn't ever be different than the type of the FixedSizeList.

Though, this answer is so obvious I doubt I'm answering your question. Tell me if I missed something.


A list is by definition a variable size container. Why don't you simply use the array class?


It's difficult to say precisely whether this is a good solution, but superficially, it looks ok (compiler errors notwithstanding). Although I'm not quite sure why you'd want a fixed-size list; isn't the whole point of a list that you can dynamically resize it? Why not just an array/vector?

As for your compilation problems, you don't need the template <typename T> for the inner class; this is already part of a template, and T is already known. Also, you have no default constructor for Node, so Node m_data[N] won't compile.

0

精彩评论

暂无评论...
验证码 换一张
取 消