codescracker


c++

C++ Templates



« Previous Tutorial Next Tutorial »


Templates in C++, are basically the foundation of the generic programming, that involves, writing the code, that is independent of any specific type.

C++ Template Example

Here is an example program illustrating templates in C++:

/* C++ Templates - Example Program */

#include<iostream.h>
#include<string.h>
#include<conio.h>
template <typename T>
inline T const& Max(T const& num1, T const& num2)
{
return num1<num2?num2:num1;
}
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"Max("<<a<<", "<<b<<"): "<<Max(a, b)<<"\n";
getch();
}

Here is the sample run of the above C++ program:

Enter any two number: 20
10
Max(20, 10): 20

Here is another example program, also demonstrating the template in C++

/* C++ Templates - Example Program */

#include<iostream.h>
#include<vector.h>
#include<conio.h>
#include<cstdlib.h>
#include<stdexcept.h>
#include<string.h>
using namespace std;
template <class T>
class STACK
{
private:
vector<T> elem;
public:
void push(T const&);
void pop();
T top() const;
bool empty() const
{
return elem.empty();
}
};
template <class T>
void STACK<T>::push(T const& ele)
{
elem.push_back(ele);
}
template <class T>
void STACK<T>::pop()
{
if(elem.empty())
{
throw out_of_range("STACK<>::pop():empty stack");
}
elem.pop_back();
}
template <class T>
T STACK<T>::top() const
{
if(elem.empty())
{
throw out_of_range("STACK<>::top():empty stack");
}
return elem.back();
}
void main()
{
clrscr();
try
{
STACK<int> intstack;
STACK<string> stringstack
intstack.push(9);
cout<<instack.top()<<"\n";
stringstack.push("Hello");
cout<<stringstack.top()<<std::endl;
stringstack.pop();
stringstack.pop();
}
catch(exception const& e)
{
cerr<<"Exception: "<<e.what()<<"\n";
getch();
exit(1);
}
getch();
}

Below is the sample run of the above C++ program:

9
Hello
Exception: STACK<>::pop():empty stack

« Previous Tutorial Next Tutorial »


Latest 5 Posts by CodesCracker




Tools
Calculator

Quick Links
Signup - Login - Give Online Test