Skip to content

Commit 3b40da8

Browse files
committed
Templates in CPP
1 parent e4f93f7 commit 3b40da8

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Templates_in_CPP.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
Question : What is template in C++? and Why we use it?
3+
4+
Answer : Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
5+
6+
Question : What is the syntax of template in C++?
7+
8+
template <class T>
9+
class className
10+
{
11+
Body of the class
12+
};
13+
*/
14+
15+
#include <iostream>
16+
using namespace std;
17+
18+
template <class T>
19+
T add(T a, T b)
20+
{
21+
return a + b;
22+
}
23+
int main()
24+
{
25+
int a = 10, b = 20;
26+
cout << "Sum of a and b is " << add(a, b) << endl;
27+
28+
float c = 10.5, d = 20.5;
29+
cout << "Sum of c and d is " << add(c, d) << endl;
30+
return 0;
31+
}
32+
33+
// ************* Template in Class *************
34+
35+
#include <iostream>
36+
using namespace std;
37+
38+
template <class T>
39+
class Arithmetic
40+
{
41+
private:
42+
T a;
43+
T b;
44+
45+
public:
46+
void add(T a1, T b1)
47+
{
48+
cout<<"The sum of Number is : " <<a1 + b1<<endl;
49+
}
50+
void sub(T a1, T b1)
51+
{
52+
cout<<"The Subtraction of Number is : " <<a1 - b1<<endl;
53+
}
54+
};
55+
56+
int main()
57+
{
58+
59+
Arithmetic<int> ar;
60+
ar.add(37,4);
61+
ar.sub(266,7);
62+
63+
Arithmetic<float> ar1;
64+
ar1.add(32.56,34.23);
65+
ar1.sub(90.98,465.97);
66+
67+
return 0;
68+
}

0 commit comments

Comments
 (0)