More c++ help..DOH! error when creating an instance of a templated stack

bigshooter

Platinum Member
Oct 12, 1999
2,157
0
71
So i wrote a templated stack to use with a program that unfortunately is due tomorrow, yes I am an idiot. I then wrote a simple test program for it, but I am getting an unfamilar compiler error.

#include <IOSTREAM.H>
#include "stack.h"
int main()
{
Stack <int> test;
for (int i=0; i<=11; ++i)
{
test.push(i);
}
for (int i=0; i<11; --i)
{
cout << "Peek " << test.peek() << endl;
}
for (int i=0; i<13; --i)
{
cout << "Pop " << test.pop() << endl;
}
return 0;
}

this is the error i get when i compile now

`g++: Compilation of header file requested
Anyone know why I'm getting this?

I think i fixed the other one, i forgot to declare what type of stack it would be <int>.
 

helppls

Senior member
Jun 19, 2001
216
0
76
hmm... well... this code looks fine... seeing stack.h may help... double-check that all your templated code is in the header file... double check the stupid errors... that it's 'class Stack' and not 'class stack' or 'class Stack<class t>'... i don't see anything else that could go wrong... another problem may be a crappy makefile...
 

PCHPlayer

Golden Member
Oct 9, 2001
1,053
0
0
When you instantiate a template the compiler must find the implementation somewhere. Some developers will put the code right in the ".h" file, others will write a separate .cpp file. In the first case the compiler just replicates the code in the .h and places it in some ".o" file. The second case is compiler dependent. On Solaris I would put the .cpp in a public directory then point the compiler to use using the -I flag.
My guess is that the stack implementation is in a .cpp file somewhere and the compiler cannot find it.
 

bigshooter

Platinum Member
Oct 12, 1999
2,157
0
71
I was just making stupid mistakes again. I thought I renamed my old makefile using the nontemplated stack, but I was still using it. I moved all my function definitions to the header file when I templated the stack, and was still trying to compile using the .h file. It was an ok makefile, just for the wrong files :p.

When you write a templated class, dont you HAVE to put the code in the header? I thought you couldnt use a .cpp file. That's the way I learned it at least.
 

PCHPlayer

Golden Member
Oct 9, 2001
1,053
0
0
No you do not have to put the code in the .h file. Most compilers will search for a file with a C++ extension with the name of the template (Stack.cpp in your case). It will instantiate the template using this code. Try separating your code from the .h file in the same directory as your main program, it should work.