Introduction to Template in C++:
1. Templates are powerful features of C++ which allows you to write generic programs.
2. We can create a single function or a class to work with different data types using templates.
3. Templates are used in the larger codebase for the purpose of code reusability and flexibility of the programs.
4. Templates can be used in two different ways like Function Templates and Class Templates.
Function Template:
1. Function template works in a similar to a normal function, with one key difference.e it can work with different data types at once. Generally, if you need to perform identical operations on two or more types of data, we need function overloading to create two functions with the required function declaration.So, it's better to use function templates because you can perform the same task writing less and maintainable code.
Declaration a function template:
Function template starts with the keyword template followed by template parameters inside < > which is further followed by function declaration.
In the below declaration, T is a template argument that accepts different data types (int, float, char) and class is a keyword.
You can also use keyword typename instead of class while declaration of template.
When arguments of any data type are passed to function_name( ) then compiler automatically generates a new version of function_name() for the given data type.
template <class T>
T function_name(T argument, T argument, ....... , T argument)
{
.... ... ....
.... ... ....
}
Example of Function Template:
1. Write a program to display greater number among two numbers using function templates.
Program Code:
#include <iostream>
using namespace std;
// template function
template <class T>
T Greater(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i, j;
float f, g;
cout << "Enter two integers number:\n";
cin >> i >> j;
cout << Greater(i, j) <<" is Greater." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f >> g;
cout << Greater(f, g) <<" is Greater." << endl;
return 0;
}
Post A Comment:
0 comments: