Member functions of a template class that take a template type as an argument

I have a node class and stack class. When I put the definition of "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 in 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;  
};

Implementation of Push (T) data:

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;
}

Change The solutions worked, except that now I get a binding error whenever I try to call functions.

Stack<int>::Pop", referenced from   
_main in main.o   
symbol(s) not found.

if definitions are not specified in Stack.h instead of Stack.cpp

+1
source share
3 answers

You need to use again template <class T>(and then use this again Tas a 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;
}
+4
source

-, ...

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;
}

( , .)

+4

This is 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 */}
+2
source

Source: https://habr.com/ru/post/1795400/


All Articles