Queue Template

What is wrong with my code?
I can't figure it out.
It compiles when I declare a QueueTp object but when I try to use the member function enqueue, it does not compile anymore.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>

template<typename T>
class QueueTp
{
private:
    int maxSize; //max number of elements
    int size;  //number of elements
    T * arr;
    int front; //where to take out the next element
public:
    QueueTp(int n = 10): size(0), front(0), maxSize(n) {arr = new T [maxSize];}
    ~QueueTp() {delete [] arr;}
    bool isempty() const {return (size == 0);}
    bool isfull() const {return size == maxSize;}
    int queucount() const {return size;}
    bool enqueue(const T & item);
    bool dequeue(T & item);
    T & endofqueue (){return arr[(front + size - 1) % maxSize];}
};


int main()
{
    QueueTp<int> myQueue;
    int i = 5;
    myQueue.enqueue(i);
}

template<typename T>
bool QueueTp<T>::enqueue(const T & item)
{
    if (isfull())
        return false;
    else
    {
        arr[(front + size) % maxSize] = item;
        size++;
        return true;
    }
}

template<typename T>
bool QueueTp<T>::dequeue(T & item)
{
    if (isempty())
        return false;
    else
    {
        item = arr[front];
        front = (front + 1) % maxSize;
        size --;
        return true;
    }
}
The provided code compiles fine for me.

You're going to need to be more specific about the error you're getting.
I put the code on one page above but actually it is in 3 files, the main file, a secondary file and .h file.
The error I get is:

Undefined symbols for architecture x86_64:
"QueueTp<int>::enqueue(int const&)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I emptied my function dequeue and I still get the same error. So it is not something in the code of the function. Very strange!
I put the definition of my functions in my main file and now it compiles. I don't understand why the files are not linked properly when I put them in the separate file. I have done it many times before.
I found what the problem is!
I can't put my member function definitions for the template class QueueTp in a separate .cpp file, I must put them in the .h file of QueueTp or in main.cpp.
According to the book C++ primer, the reason is that the template member functions are not really member functions but instructions to the compiler on how to generate member functions for a particular instantiation.
Last edited on
AbstractionAnon, thank you for your help!
Topic archived. No new replies allowed.