how to write a template c++
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int x = 5, y = 10;
float f1 = 2.5, f2 = 3.5;
cout << "Adding integers: " << add(x, y) << endl;
cout << "Adding floats: " << add(f1, f2) << endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library to enable input and output operations.using namespace std;
: Allows access to entities such as cout and endl within the std namespace without prefixing them withstd::
.template <typename T>
: Defines a template for a function namedadd
that takes a typeT
as a parameter.T add(T a, T b) {...}
: This is the template functionadd
, which takes two parameters of typeT
and returns their sum of typeT
.int main() {...}
: The main function where the program execution begins.int x = 5, y = 10;
: Declaration and initialization of two integer variablesx
andy
.float f1 = 2.5, f2 = 3.5;
: Declaration and initialization of two float variablesf1
andf2
.cout << "Adding integers: " << add(x, y) << endl;
: Calls theadd
function with integer parametersx
andy
and displays the result using cout.cout << "Adding floats: " << add(f1, f2) << endl;
: Calls theadd
function with float parametersf1
andf2
and displays the result using cout.return 0;
: Indicates successful program execution and termination of themain
function.