模板使用另一个模板

template using another template

本文关键字:另一个      更新时间:2023-10-16

以下是模板列表代码的精简版本(改编自http://www.daniweb.com/software-development/cpp/threads/237391/c-template-linked-list-help)

List抱怨(编译错误)"Node不是类型"。为什么会这样,解决方法是什么?

我尝试将"类节点"替换为"结构节点"(以及相关更改),结构版本运行良好。因此,主要问题似乎是:一个模板类如何访问另一个模板类别?

#include <iostream>
using namespace std;
template <typename T>
class Node
{
    public:
        Node(){}
        Node(T theData, Node<T>* theLink) : data(theData), link(theLink){}
        Node<T>* getLink( ) const { return link; }
        const T getData( ) const { return data; }
        void setData(const T& theData) { data = theData; }
        void setLink(Node<T>* pointer) { link = pointer; }
    private:
        T data;
        Node<T> *link;
};
template <typename T>
class List {
    public:
        List() {
            first = NULL; 
            last = NULL;
            count = 0;
        }
        void insertFirst(const T& newData) {
            first = new Node(newData, first);
            ++count;
        }
        void printList() {
            Node<T> *tempt;
            tempt = first;
            while(tempt != NULL){
                cout << tempt->getData() << " ";
                tempt = tempt->getLink();
            }
        }
        ~List()  { }
    private:
        Node<T> *first;
        Node<T> *last;
        int count;
};
int main() {
    List<int> myIntList;
    cout << "Inserting 1 in the list...n";
    myIntList.insertFirst(1);
    myIntList.printList();
    cout << endl;
    List<double> myDoubleList;
    cout << "Inserting 1.5 in the list...n";
    myDoubleList.insertFirst(1.5);
    myDoubleList.printList();
    cout << endl;
}

您正在使用

new Node(newData, first); 

在CCD_ 1模板内。在这一点上,Node不是指类型,而是指模板。当然,要创建一个带有new的类型实例,您需要一个类型。

您最可能要做的事情是通过实例化模板使其成为一种类型,即

new Node<T>(newData, first);
相关文章: