Not only can you use templates for a primitive data type within functions, but also within classes.
Consider the following example:
template<typename T>
class Stack
{
public:
Stack();
bool isEmpty() const;
T peek() const;
void push(T value);
T pop();
int getSize() const;
private:
T elements[100];
int size;
};
The methods are similar to a non-template class, however, each method is a template itself, so you have to adjust a few things. For example, you have to specify template<typename T>
before each method. Also the prefix is now Stack<T>::
.
template<typename T>
Stack<T>::Stack() {
//...
}
template<typename T>
bool Stack<T>::isEmpty() {
// ...
}
template<typename T>
T Stack<T>::peek() {
// ...
}
You’d need to declare your data type when you build your object from your template:
Stack<int> intStack;
// example of building from a generic template with a specific type.
Class Templates was originally found on Access 2 Learn