Hi Template Questions

I have a template question about my program.I put my question in the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void Interface::unsorted_interger_list()
{
    bool isQuit = false;
    while(!isQuit)
    {
        ///I declare a List<int>* mylist in Interface.h file and call 
        ///the funcions which belong to the class List.
        mylist->print();///error: undefined reference to 'List<int>::print()'
                        ///But I defined my funtion in Class:List. 
                        ///Why it doesn't work?

        unsorted_list_menu();
        int choice = reader.readInt(0, 10);
        if(choice == 0)
        {
            isQuit = true;
        }
        else if(choice == 1)
        {
            cleanstreen();
            cout<<"Input value from front:\n";
            int data = reader.readInt();
            mylist->pushFront(data);
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Interface
{
public:
    void project();
    void unsorted_interger_list();
    void sorted_interger_list();
    void unsorted_datathing_list();
    void sorted_datathing_list();
    void sorted_list_menu();
    void unsorted_list_menu();
private:
    CinReader reader;
    List<int>* mylist;
///    List<DataThing>* datalist;
    void cleanstreen();
};

1
2
3
4
5
6
7
8
9
10
11
12
template <class TYPE>
class List
{
    public:
    List();
    ~List();
    void print();

    private:
    unsigned int m_nodeCount;
    Node<TYPE>* m_head;
    Node<TYPE>* m_tail;

1
2
3
4
5
6
7
8
9
10
11
12
13
template <class TYPE>
void List<TYPE>::print()
{
    Node<TYPE>* ptr=m_head;
    int i=1;
    while(ptr!=NULL)
    {
        cout<<"["<<i<<"]"<<ptr->getData()<<"->";
        ptr=ptr->getNext();
        i++;
    }
    cout<<endl;
}
Last edited on
You must implement functions like print() within the templated class
I found I could implement them outside the template class, provided they were still in the header file, but with large template headers it does get very messy.
You can move the implementation on an external file, but then you'll have to include it in the header.
This way you can keep the code more organized
Is the normal rule that functions implemented inside the class declaration are inline and those outside are non inline still applicable for template classes? (Assuming the compiler doesn't overrule your judgement...)
Topic archived. No new replies allowed.