2

Possible Duplicate:
Why can templates only be implemented in the header file?
“Undefined symbols” linker error with simple template class

queue.h

#include<iostream>
using namespace std;

template <class t>
class queue {  

    public:  
        queue(int=10);  
        void push(t&);  
        void pop();  
        bool empty();    

    private:  
        int maxqueue;  
        int emptyqueue;  
        int top;  
        t* item;  
};  

queue.cpp

#include<iostream>

#include"queue.h"
using namespace std;

template <class t>
queue<t>::queue(int a){
    maxqueue=a>0?a:10;
    emptyqueue=-1;
    item=new t[a];
    top=0;
}

template <class t>
void queue<t>::push(t &deger){

    if(empty()){
        item[top]=deger;
        top++;
    }
    else
        cout<<"queue is full";
}
template<class t>
void queue<t>::pop(){
    for(int i=0;i<maxqueue-1;i++){
        item[i]=item[i+1];
    }
    top--;
    if(top=emptyqueue)
        cout<<"queue is empty";
}
template<class t>
bool queue<t>::empty(){
    if((top+1)==maxqueue)
        return false
    else
        return true 
}

main.cpp

#include<iostream>
#include<conio.h>

#include"queue.h"
using namespace std;

void main(){
    queue<int>intqueue(5);
    int x=4;
    intqueue.push(x);

    getch();
}

I have created queue using template. Compiler gave this errors. I couldn't solve this problem.

1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall queue::push(int)" (?push@?$queue@H@@QAEXH@Z) referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall queue::queue(int)" (??0?$queue@H@@QAE@H@Z) referenced in function _main 1>c:\users\pc\documents\visual studio 2010\Projects\lab10\Debug\lab10.exe : fatal error LNK1120: 2 unresolved externals

EDIT: Solution is given in here.

Community
  • 1
  • 1
Candost
  • 1,029
  • 1
  • 12
  • 28
  • http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file might have been better – Flexo May 03 '12 at 18:46

2 Answers2

0

Put all the template related queue implementation in the header file. Just like: Why can templates only be implemented in the header file?

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
0

Template classes cannot be separated into .cpp and .h files because the compiler requires a copy of the implementation in order to generate the desired class from the template.

You need to move the contents of queue.cpp into queue.cpp

Matt Kline
  • 10,149
  • 7
  • 50
  • 87