cpp template
#include <iostream>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int x = 5, y = 10;
float p = 3.5, q = 2.5;
std::cout << "Adding integers: " << add(x, y) << std::endl;
std::cout << "Adding floats: " << add(p, q) << std::endl;
return 0;
}
This C++ code demonstrates the use of templates.
Header Inclusion: The code includes the necessary header file
<iostream>
for input and output operations.Template Function: A template function
add
is declared using thetemplate
keyword and the<typename T>
syntax to define a generic typeT
. This function takes two parameters of typeT
and returns their sum.Main Function: Inside the
main()
function, variablesx
,y
(of typeint
),p
,q
(of typefloat
) are declared and initialized with values.Function Calls: The
add
function is called twice:add(x, y)
adds two integers and prints the result.add(p, q)
adds two floats and prints the result.Output: The
std::cout
statements display the results of the addition operations on the console.Return: The
main()
function returns 0, indicating successful execution. ```