Reputation: 83
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() {
Upvotes: 1
Views: 665
Reputation: 24768
Both push()
and pop()
are (non-template) member functions of the Stack
class template. Since this class template, Stack
, is parameterized by a type template parameter (i.e.: T
), so are those member functions as well.
Therefore, the implementation of those member functions needs a type template parameter:
template<typename A>
void Stack<A>::push(const A& t) { ... }
template<typename B>
void Stack<B>::pop() { ... }
Note that the name of the template parameter is actually irrelevant (A
and B
above).
Note as well that the name of the class template Stack
not followed by any template arguments inside the body of its definition is equivalent to the class template with its template parameter as the template argument, i.e.: Stack<T>
.
Upvotes: 2
Reputation: 206627
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.
Upvotes: 5