Member functions of a templated class, that take a template type as argument
I have a node struct and stack class. When I put the def开发者_JAVA技巧inition for 'void Push(T data)' outside the class definition I get:
error: 'template<class T> class Stack' used without template parameters
But when I put it inside the class definition it works fine.
Here is the code:template <class T>
struct Node
{
Node(T data, Node <T> * address) : Data(data), p_Next(address) {}
T Data;
Node <T> * p_Next;
};
template <class T>
class Stack
{
public:
Stack() : size(0) {}
void Push(T data);
T Pop();
private:
int size;
Node <T> * p_first;
Node <T> * p_last;
};
The implementation for Push(T data) is :
void Stack::Push(T data)
{
Node <T> * newNode;
if(size==0)
newNode = new Node <T> (data, NULL);
else
newNode = new Node <T> (data, p_last);
size++;
p_last = newNode;
}
Edit: The solutions worked except that now I get a linking error whenever I try to call the functions.
Stack<int>::Pop", referenced from
_main in main.o
symbol(s) not found.
unless the definitions are in Stack.h instead of Stack.cpp
You need to use the template <class T>
again (and then use that T
again as the template parameter for the class):
template <class T>
void Stack<T>::Push(T data)
{
Node <T> * newNode;
if(size==0)
newNode = new Node <T> (data, NULL);
else
newNode = new Node <T> (data, p_last);
size++;
p_last = newNode;
}
You need to add a template statement before member functions when defined outside of the class...
template <class T>
void Stack<T>::Push(T data)
{
Node <T> * newNode;
if(size==0)
newNode = new Node <T> (data, NULL);
else
newNode = new Node <T> (data, p_last);
size++;
p_last = newNode;
}
(At least it should be similar to this.)
That's because when the definition is inside the class definition it knows the template parameter. If you want to put the definition outside you need to explicitly tell the compiler that T is a template parameter...
template <class T>
void Stack<T>::Push(T data) {/* code */}
精彩评论