使用模板在 class(双向链表)中定义结构

Defining a struct within a class (doubly linked list) using a template

我已经为此 class 实现了每个方法,但我正在努力解决最后一个错误。我得到了在 class 链表的私有部分中定义节点结构的说明。我收到如下错误:

"error: Node is not a class template"

"error: non-template type 'Node' used as a template"

如果我重新排列事物并将 Node 结构完全放在 class 之外,我的代码就可以工作,但这并不是我真正想要的解决方案。

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

typedef int element_type;

template<class element_type>
class linkedlist
{
private:

    struct Node<element_type>{
        Node<element_type>* next;
        Node<element_type>* prev;
        element_type data;
    };
    Node<element_type>* head;
    Node<element_type>* tail;
    unsigned int size;

public:

    linkedlist();
    ~linkedlist();
    void push_back(const element_type& z);
    void push_front(const element_type& z); //add front
    void print() const;

    // will initialize list with n nodes
    explicit linkedlist(unsigned int n);
};

只需从结构节点中删除模板参数。

struct Node {
    Node * next;
    Node * prev;
    element_type data;
};
Node * head;
Node * tail;
unsigned int size;

TL;DR 版本是在 Node:

上删除模板语法
struct Node{
    Node* next;
    Node* prev;
    element_type data;
};
Node* head;
Node* tail;

因为Node定义在class模板内部,它已经可以访问类型element_type。编译器错误只是告诉您在声明本身不是模板的结构时不能使用模板语法。