I am doing some exercises and tried to convert a simple class into a template class.
After changing the code I wound up with a bunch of linker errors and so I removed the header file inclusion statement from the implementation and now include the implementation file at the bottom of the header file. Ever since then I get this strange syntax error: missing ‘;’ before ‘<‘. I can’t see what I am doing wrong.
This is my header file:
#ifndef STACK_H
#define STACK_H
#include <iostream>
template<class T>
class Stack
{
T* buffer;
size_t count;
public:
Stack();
~Stack();
void push(T value);
void pop();
T top() const;
size_t size() const;
};
#include "Stack.cpp"
#endif
And this is the implementation file:
template<class T>
Stack<T>::Stack() : count(0)
{
buffer = new T;
}
template<class T>
Stack<T>::~Stack()
{
delete[] buffer;
}
template<class T>
void Stack<T>::push( T value )
{
if(size() == 0) *(buffer) = value;
else
{
T* newBuffer = new T[count+1];
for(size_t i=0; i <= size(); ++i)
newBuffer[i] = buffer[i];
newBuffer[count] = value;
buffer = newBuffer;
}
++count;
}
template<class T>
void Stack<T>::pop()
{
if(size() <= 0) return;
buffer[size()-1]=0;
--count;
}
template<class T>
typename T Stack<T>::top() const
{
if(size() <= 0)
{
std::cout << "the stack is empty" << std::endl;
return -1;
}
else
{
return buffer[size()-1];
}
}
template<class T>
size_t Stack<T>::size() const
{
return count;
}
Any help would be appreciated !!!
My guess is that you’re attempting to compile the
.cppfile. Despite the confusing file extension, it isn’t a complete translation unit, so it can’t be compiled by itself. Just include the header from any file that uses the class.Personally, I’d move the implementation into the header file; others might give it a different file extension that doesn’t look like a compilable source file (I’ve seen
.tccand.inlused for such files, but there’s no universal convention).Also:
Remove that
typename; you only put that before a type name that depends on a template parameter.