Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to write the template angle brackets (<...>)?

Given this example class template:

template<typename T>
class Stack {
    T * data;
    int size;
    int nextIndex;
public:
    Stack(int size = 100);
    Stack(const Stack& stack);
    ~Stack();
    Stack& operator=(const Stack& s);
    void push(const T& t);
    void pop();
    T& top();
    const T& top() const;
    int getSize() const;

    class Full {
    };
    class Empty {
    };
};

template<typename T>
void Stack::push(const T& t) {
    if (nextIndex >= size) {
        throw Full();
    }
    data[nextIndex++] = t;
}
 
template<typename T>
void Stack::pop() {
    if (nextIndex <= 0) {
        throw Empty();
    }
    nextIndex--;
}  

Is it ok the part of the implementaion of the push and pop methods?

I don't understand if I need to write void Stack<T>::push(const T& t) instead of void Stack::push(const T& t) (and the same for the pop method).

NOTE: Eclipse (according to C++11) gives me the next error:

Member declaration not found

because of these lines:

void Stack::push(const T& t) { 
void Stack::pop() {
like image 375
J.Roe Avatar asked Mar 12 '26 16:03

J.Roe


1 Answers

The part of the implementaion of push method and pop method it's ok? I don't understand if I need to write void Stack::push(const T& t) instead void Stack::push(const T& t) (and the same for pop method).

You need to use

template <typename T>
void Stack<T>::push(const T& t) { ... }

template <typename T>
void Stack<T>::pop() { ... }

The name Stack is the same as Stack<T> inside the class template definition when it is used as a typename. Outside the class template definition, you have to supply the template parameter explicitly.

like image 172
R Sahu Avatar answered Mar 15 '26 05:03

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!