#include <iostream>
template<typename T,int size>
class Stack {
	T m_Buffer[size];
	int m_Top{ -1 };
public:
	Stack() = default;
	Stack(const Stack<T, size> &obj) {
		m_Top = obj.m_Top;
		for (int i = 0; i <= m_Top; ++i) {
			m_Buffer[i] = obj.m_Buffer[i];
		}
	}
	void Push(const T &elem) {
		m_Buffer[++m_Top] = elem;
	}
	void Pop();
	const T& Top()const {
		return m_Buffer[m_Top];
	}
	bool IsEmpty() {
		return m_Top == -1; 
	}
	/*
	Shorthand notation for class name as return type,
	because it appears inside the class
	*/
	static Stack Create();
};

template<typename T, int size>
void Stack<T, size>::Pop() {
	--m_Top;
}

template<typename T, int size>
/*
Longhand notation for class name as return type,
because it appears outside the class
*/
Stack<T, size> Stack<T, size>::Create() {
	return Stack<T, size>();
}
int main() {
	/*
	The template parameter list is part of the type of class.
	The following code will not work.

	Stack<float, 9> s = Stack<float, 10>::Create();
				 ^
	*/
	Stack<const char *, 5> ss2 ;
	ss2.Push("Hello") ;
	
	Stack<float, 10> s = Stack<float, 10>::Create();
	s.Push(3);
	s.Push(1);
	s.Push(6);
	s.Push(9);
	auto s2(s);
	while (!s2.IsEmpty()) {
		std::cout << s2.Top() << " ";
		s2.Pop();
	}
	Stack<char *, 5> ss;
	ss.Push("Hello");
	return 0;
}

This code is an example of a C++ template class Stack that can be used to create stack data structures of any type and size. A stack is a data structure that follows the LIFO (Last In, First Out) principle, where the last element pushed onto the stack is the first element to be popped off.

The template class Stack has two template parameters: T which represents the type of the elements in the stack, and size which represents the maximum number of elements that can be stored in the stack.

The class has the following public member functions:

Push(const T &elem): pushes an element of type T onto the stack.
Pop(): removes the top element from the stack.
Top(): returns a reference to the top element of the stack, without removing it from the stack.
IsEmpty(): returns true if the stack is empty, false otherwise.
The class also has a static member function Create() which creates an instance of the Stack and returns it.

The class also has a copy constructor which is used to copy the stack.

In the main function, the code creates an instance of the stack using the Create() method, pushes some elements on it and then it pops the elements and prints them.

It's important to note that the size of the stack is passed as a non-type template parameter, it means that the size of the stack must be known at compile-time, this means you can't use this class with dynamically allocated stacks. Also, the class can't store a variable number of elements, it can only store the number of elements specified by the size template parameter.



Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: