Templates – when to use them
Templates are a C++ programming way to lay the foundations for writing a generic program. Using templates, we can write code in such a way that it is independent of any particular data type. We can use function templates or class templates.
Getting ready
For this recipe, you will need a Windows machine with a working copy of Visual Studio.
How to do it…
In this recipe, we will find out the importance of templates, how to use them, and the advantages that using them provides us.
Open Visual Studio.
Create a new C++ project.
Add source files called
Source.cpp
andStack.h
.Add the following lines of code to
Source.cpp
:#include <iostream> #include <conio.h> #include <string> #include "Stack.h" using namespace std; template<class T> void Print(T array[], int array_size) { for (int nIndex = 0; nIndex < array_size; ++nIndex) { cout << array[nIndex] << "\t"; } cout << endl; } int main() { int iArray[5] = { 4, 5...