R71
R71

Reputation: 4523

template using another template

Here is a cut-down version of a template List code (adapted from http://www.daniweb.com/software-development/cpp/threads/237391/c-template-linked-list-help)

List complains (compile error) that "Node is not a type". Why is this, and what is the fix?

I tried replacing the "class Node" with a "struct Node" (and related changes), and the struct version worked fine. So the main question seems to be: how does a template-class access another template-class?

#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;
}

Upvotes: 2

Views: 113

Answers (1)

PlasmaHH
PlasmaHH

Reputation: 16046

You are using

new Node(newData, first); 

within the List template. At that point, Node does not refer to a type, but to a template. But of course to create an instance of a type with new, you need a type there.

The most probable thing you want to do is to make it a type by instantiating the template, i.e.

new Node<T>(newData, first);

Upvotes: 3

Related Questions