C++/Templates 2

< C++

Templates 2

Templates can also be used with classes

using namespace std;
 
template <class T>
class myClass
{
		// Attributes
		T * storage;
		int NElements;
	public:
		// Constructors & Destructor
		myClass(int size = 1)
		{
			storage = new T[size];
			NElements = size;
		}
		~myClass() {delete [] storage;}
		// Methods
		int GetSize() {return NElements;}
		T GetVal(int place) {return storage[place];}
 
		void SetVal(int place, T val)
		{
			if (place + 1 > NElements)
			{ cout << "Cannot place a value at position " << place << endl; return; }
			storage[place] = val;
		}
		void push(T val) { SetVal(NElements++, val); }
		void pop() { NElements--; }
};
int main()
{
	myClass<int> mc1;
	for (int i = 0 ; i < 10 ; i++)
		{ mc1.push((i + 1)*(i + 1)); }
 
	for (int i = 0; i < mc1.GetSize() ; i++)
		{ cout << mc1.GetVal(i) << endl; }
 
	cout << "-------------\n";
 
	myClass<char> mc2;
	for (int i = 0 ; i < 26 ; i++)
		{ mc2.push((char) i+97); }
 
	for (int i = 0; i < mc2.GetSize() ; i++)
		{ cout << mc2.GetVal(i) << endl; }
 
	return 0;
}

Where To Go Next

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science
This article is issued from Wikiversity - version of the Saturday, November 30, 2013. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.