分配器错误

问题描述 投票:1回答:1
namespace Test
{
    template <typename DataType, typename Allocator = std::allocator<DataType>>
    class List 
    {
    private:
        struct Node
        {
            Node* next;
            DataType Data;
            Node(DataType Data,Node* next = nullptr);
        };

        typename Allocator::template rebind<Node*>::other allocator;
        Node* head;
        int size;

    public :
        List();
        ~List();

        void PushFront(DataType Data);
        //void Insert(DataType Data, size_t index);
        //void DeleteByIndex(size_t index);

        template <typename DataType, typename Allocator = std::allocator<DataType>>
        friend std::ostream& operator<<(std::ostream& out, Test::List<DataType, Allocator> list);
    };

    template<typename DataType, typename Allocator = std::allocator<DataType>>
    std::ostream& operator<<(std::ostream& out, Test::List<DataType, Allocator> list)
    {
        typename decltype(list)::Node* current = list.head;
        for (size_t i = 0; i < list.size; ++i)
        {
            out << current.Data << " ";
            current = current->next;
        }
    }
    template<typename DataType, typename Allocator>
    inline List<DataType, Allocator>::Node::Node(DataType Data,Node* next) :
        Data(Data),
        next(next)
    {}

    template <typename DataType, typename Allocator>
    Test::List<DataType, Allocator>::List() :
        head(nullptr),
        size(NO_SIZE)
    {}

    template <typename DataType, typename Allocator>
    Test::List<DataType, Allocator>::~List()
    {
        Node* help = head->next;
        for (size_t i = 0; i < size; ++i)
        {
            allocator.destroy(head);
            allocator.deallocate(head, 1);
            head = help;
            help = help->next;
        }
    }

    template <typename DataType, typename Allocator>
    void Test::List<DataType, Allocator>::PushFront(DataType Data)
    {
        Node* newHead = allocator.allocate(1);
        allocator.construct(newHead, Data, head);
        head = newHead;
    }

在主界面上,我试图让这个列表

int main()
{
    Test::List<int> l;
    l.PushFront(10);
    l.PushFront(20);
}

我得到的错误。

C2664 "void std::allocator<_Other>::deallocate(_Ty *const ,const size_t)": impossuble to convert first argument from "Test::List>::Node *" in "_Ty *const" in this string(allocator.deallocate(head, 1);)

C2440初始化:无法将 "Test::List>:Node "中的"_Ty *"转换为 "Test::List>:Node "中的"_Ty *const"。"在这个字符串(Node newHead = allocator.allocate(1);)

如何解决这个问题(错误是我翻译的,如果有错误请见谅)

c++ templates memory-management
1个回答
0
投票

尝试改变

typename Allocator::template rebind<Node*>::other allocator;

typename Allocator::template rebind<Node>::other allocator;

指针是隐式的。

另外,你应该使用 std::allocator_traits 与分配器一起使用,而不是直接使用分配器的类型定义和函数。

© www.soinside.com 2019 - 2024. All rights reserved.