c++ template
#include <iostream>
// Step 1: Define a template function
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
// Step 2: Instantiate the template function with specific types
int result_int = add(3, 5);
double result_double = add(2.5, 4.7);
// Step 3: Display the results
std::cout << "Integer Addition Result: " << result_int << std::endl;
std::cout << "Double Addition Result: " << result_double << std::endl;
return 0;
}
Explanation:
1. Include the necessary header file (#include <iostream>
) for input/output operations.
Define a template function using the
template
keyword followed by the template parameter<typename T>
. This function, namedadd
, takes two parameters of the same typeT
and returns their sum.In the
main
function:- Instantiate the template function with specific types (
int
anddouble
). Store the results of the function calls in variables (
result_int
andresult_double
).Display the results using
std::cout
and the<<
operator.The program returns 0 to indicate successful execution.