Example : A Templates Program Examples in C++ to show Function Template.
#include <iostream>
template<typename T>
T maxval(T a, T b) {
return a > b ? a : b;
}
int main() {
int a = 100, b = 50;
double x = 113.414, y = 210.071;
std::cout << "The larger value is = " << maxval(a, b) << std::endl;
std::cout << "The larger value is = " << maxval(x, y) << std::endl;
return 0;
}
Output:
The larger value is = 100
The larger value is = 210.071
----------- OR -----------
#include <iostream>
using namespace std;
template<class T>
T addition(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int x =200;
int y =30;
float p = 20.34;
float q = 100.02;
cout<<"Addition of x and y is :"<<addition(x,y);
cout<<'\n';
cout<<"Addition of p and q is :"<<addition(p,q);
return 0;
}
Output:
Addition of x and y is :230
Addition of p and q is :120.36
-------- OR --------
#include <iostream>
using namespace std;
template<class A>
void Display(A a)
{
std::cout << "Value of a is = : " <<a<< std::endl;
}
int main()
{
Display(105);
return 0;
}
Output:
Value of a is = : 105
---------- OR ----------
#include <iostream>
using namespace std;
template<class A,class B>
void Display(A a, B b)
{
std::cout << "Value of a is = : " <<a<< std::endl;
std::cout << "Value of b is = : " <<b<< std::endl;
}
int main()
{
Display(105,102.003);
return 0;
}
Output:
Value of a is = : 105
Value of b is = : 102.003
--------- OR ---------
#include <iostream>
using namespace std;
template<class A>
void Display(A a)
{
std::cout << "Value of a is = : " <<a<< std::endl;
}
template<class A,class B>
void Display(A a, B b)
{
std::cout << "Value of a is = : " <<a<< std::endl;
std::cout << "Value of b is = : " <<b<< std::endl;
}
int main()
{
Display(410.037);
Display(450,52.003);
return 0;
}
Output:
Value of a is = : 410.037
Value of a is = : 450
Value of b is = : 52.003
Example : A Templates Program Examples in C++ to show Class Template.
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 15;
T num2 = 35;
void add()
{
std::cout << "Addition of two no. is = : " << num1+num2 <<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
Output:
Addition of two no. is = : 50
---------- OR -----------
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 m;
T2 n;
public:
A(T1 x,T2 y)
{
m = x;
n = y;
}
void display()
{
std::cout << "Two values are : "<<m<<" "<<n<<std::endl;
}
};
int main()
{
A<int,float> d(54,60.05);
d.display();
return 0;
}
Output:
Two values are : 54 60.05
-------- OR --------
#include <iostream>
using namespace std;
template<class T, int size>
class A
{
public:
T arr[size];
void input()
{
int x = 100;
for (int j=0;j<size;j++)
{
arr[j] = x;
x++;
}
}
void display()
{
for(int j=0;j<size;j++)
{
std::cout << arr[j] << " ";
}
}
};
int main()
{
A<int,10> obj1;
obj1.input();
obj1.display();
return 0;
}
Output:
100 101 102 103 104 105 106 107 108 109
0 Comments