In this example, the “Stack” class template takes a type parameter “T” that represents the type of the elements that the stack can hold. The class template provides methods for pushing and popping elements onto and off of the stack, and for checking whether the stack is empty or full.
The main function demonstrates how the “Stack” class template can be used with different types of data. It creates two instances of the “Stack” class, one for integers and one for doubles. It pushes three values onto each stack, pops the values off the stack, and displays the values.
Note that the type parameter “T” is inferred from the data types of the variables used to create instances of the “Stack” class template. This allows the “Stack” class template to work with different types of data using the same code.
Class templates can be very useful when working with generic data structures and containers that can hold different types of data. The stack example demonstrates how a class template can be used to create a stack data structure that can hold any type of elements using a single class template.
#include <iostream>
template <typename T>
class Stack {
private:
T* data;
int top;
int capacity;
public:
Stack(int capacity) : data(new T[capacity]), top(-1), capacity(capacity) {}
~Stack() { delete[] data; }
void push(T value) {
if (top >= capacity - 1) {
std::cout << "Error: Stack overflow" << std::endl;
return;
}
top++;
data[top] = value;
}
T pop() {
if (top < 0) {
std::cout << "Error: Stack underflow" << std::endl;
return T();
}
T value = data[top];
top--;
return value;
}
bool is_empty() const {
return top < 0;
}
bool is_full() const {
return top >= capacity - 1;
}
};
int main() {
Stack<int> int_stack(5);
int_stack.push(10);
int_stack.push(20);
int_stack.push(30);
std::cout << int_stack.pop() << std::endl;
std::cout << int_stack.pop() << std::endl;
std::cout << int_stack.pop() << std::endl;
Stack<double> double_stack(5);
double_stack.push(1.1);
double_stack.push(2.2);
double_stack.push(3.3);
std::cout << double_stack.pop() << std::endl;
std::cout << double_stack.pop() << std::endl;
std::cout << double_stack.pop() << std::endl;
return 0;
}