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:

  1. #include <iostream>: Includes the input/output stream library to enable input and output operations.
  2. using namespace std;: Allows access to entities such as cout and endl within the std namespace without prefixing them with std::.
  3. template <typename T>: Defines a template for a function named add that takes a type T as a parameter.
  4. T add(T a, T b) {...}: This is the template function add, which takes two parameters of type T and returns their sum of type T.
  5. int main() {...}: The main function where the program execution begins.
  6. int x = 5, y = 10;: Declaration and initialization of two integer variables x and y.
  7. float f1 = 2.5, f2 = 3.5;: Declaration and initialization of two float variables f1 and f2.
  8. cout << "Adding integers: " << add(x, y) << endl;: Calls the add function with integer parameters x and y and displays the result using cout.
  9. cout << "Adding floats: " << add(f1, f2) << endl;: Calls the add function with float parameters f1 and f2 and displays the result using cout.
  10. return 0;: Indicates successful program execution and termination of the main function.