Write a C++ program to implement the following:-
• Function templates
• Class templates
PROGRAM:
FUNCTION TEMPLATES
#include<iostream .h="">
#include<conio .h="">
template <class t="">
T abs(T n)
{
return (n<0 abs="" clrscr="" cout="" double="" dub1="" dub2="" endl="" getch="" include="" int1="" int2="" int="" iostream.h="" lon1="" lon2="" long="" main="" n:n="" nabs="" output="" templates="" void="" www.adkool.com="">
#include<conio .h="">
const int MAX = 100; //size of array
template <class type="">
class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
public:
Stack() //constructor
{ top = -1; }
void push(Type var) //put number on stack
{ st[++top] = var; }
Type pop() //take number off stack
{ return st[top--]; }
};
int main()
{
clrscr();
Stack<float> s1; //s1 is object of class Stack<float>
s1.push(1111.1F); //push 3 floats, pop 3 floats
s1.push(2222.2F);
s1.push(3333.3F);
cout<<"www.adkool.com";
cout << "\nElements pushed in float\n";
cout << "------------------------";
cout << "\n\n1: 1111.1F \n\n2: 2222.2F \n\n3: 3333.3F";
cout << "\n\nElements popped \n";
cout << "---------------";
cout << "\n\n1: " << s1.pop() << endl;
cout << "\n2: " << s1.pop() << endl;
cout << "\n3: " << s1.pop() << endl;
Stack<long> s2; //s2 is object of class Stack<long>
s2.push(123123123L); //push 3 longs, pop 3 longs
s2.push(234234234L);
s2.push(345345345L);
cout << "\n\n\nElements pushed in long\n";
cout << "------------------------";
cout << "\n\n1: 123123123L \n\n2: 234234234L \n\n3: 345345345L";
cout << "\n\nElements popped \n";
cout << "---------------";
cout << "\n\n1: " << s2.pop() << endl;
cout << "\n2: " << s2.pop() << endl;
cout << "\n3: " << s2.pop() << endl;
getch();
return 0;
}
OUTPUT
Elements pushed in float
------------------------
1: 1111.1F
2: 2222.2F
3: 3333.3F
Elements popped
---------------
1: 3333.300049
2: 2222.199951
3: 1111.099976
Elements pushed in long
------------------------
1: 123123123L
2: 234234234L
3: 345345345L
Elements popped
---------------
1: 345345345
2: 234234234
3: 123123123
</long></long></float></float></class></conio></0></class></conio></iostream>