11 Templates Part 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Templates in C++, part 2

1
Templates in C++, part 2
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 = 0)
{
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 an 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;
Templates in C++, part 2
2
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
Lesson 1: Introduction to C++ Lesson 8: Pointers Lesson 12: The STL
Lesson 2: Variables and User Input Lesson 9: Classes and Inheritance Lesson 13: STL Algorithms
Lesson 3: Simple Math Lesson 10: Templates 1
Lesson 4: Conditional Statements Lesson 11: Templates 2
Lesson 5: Loops
Lesson 6: Functions and Recursion
Lesson 7: More Functions
Part of the School of Computer Science
Article Sources and Contributors
3
Article Sources and Contributors
Templates in C++, part 2 Source: http://en.wikiversity.org/w/index.php?oldid=742818 Contributors: Erkan Yilmaz, Giawa, Mawootad, Remi, 4 anonymous edits
License
Creative Commons Attribution-Share Alike 3.0 Unported
//creativecommons.org/licenses/by-sa/3.0/

You might also like