Templates in C++
It is a concept which develops generic classes and functions. Using this, you can create a code that helps the user to use the code for any data type without changing the base code.
How to create templates?
Here, is the syntax.
template <typename A, typename
B, ...>
eg:
‘template <typename T> T myfunction(T a, T b,……, T n);’
Why templates?
Templates
are useful for the following functionality.
- · Reusability.
- · Data type safety.
- · It makes the implementation easy for vectors, maps and sorting.
- · Code duplication is avoided.
The types of templates are given below…
- Class
Templates
- Function
Templates
- Variable
Templates (Since C++ 14)
Let us create a template to add two numbers.
- A template mySum is created with two parameters x,y. ‘Typename’ refers datatype.
- A function definition is included as adding two numbers.
- This template uses three different data type values to call the mySum().
- Finally, all values are added and the output is displayed.
Program:
#include <iostream>
using namespace std;
template <typename T> T mySum(T x, T y)
{
return (x + y);
}
int main()
{
// Using mySum
cout <<
"Sum of 5 and 9 is: " << mySum<int>(5, 9) << endl;
cout <<
"Sum of 6.5 and 10.5 is :" << mySum<float>(6.5, 10.5)
<< endl;
cout
<<"Sum of 34.56 and 78.90 is:" <<
mySum<double>(34.56,78.90) << endl;
return 0;
}
Output:
Sum of 5 and 9 is: 14
Sum of 6.5 and 10.5 is :17
Sum of 34.56 and 78.90 is:113.46
Let us change this addition code for subtraction.
So, the template can be changed like .
template <typename T> T myDiff(T x, T y)
{
return (x - y);
}
int main()
{
// Using myDiff
cout << "Difference of 9 and 5
is: " << myDiff<int>(9, 5) << endl;
cout <<
"Difference of 6.5 and 10.5 is :" << myDiff<float>(6.5,
10.5) << endl;
cout
<<"Difference of 78.90 and 34.56 is:" <<
myDiff<double>(78.90, 34.56) << endl;
return 0;
}
When you compile and run the program, you get the below
output.
Difference of 9 and 5 is: 4
Difference of 6.5 and 10.5 is :-4
Difference of 78.90 and 34.56 is:44.34
Hope ,you understood the code. If you have any doubts,
comment me in the comments section. Keep Coding!!!
Comments
Post a Comment