C++ template example

#include <iostream>

template <class T>
T findMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int intMax = findMax(10, 5);
    double doubleMax = findMax(3.14, 2.71);

    std::cout << "Maximum of 10 and 5 is: " << intMax << std::endl;
    std::cout << "Maximum of 3.14 and 2.71 is: " << doubleMax << std::endl;

    return 0;
}
  1. The code includes the iostream library, which provides input and output operations.
  2. The template keyword is used to define a template.
  3. <class T> declares a template parameter T, which represents a generic type.
  4. The findMax function is defined using the template parameter T for its input arguments and return type.
  5. Within the findMax function, the ternary operator is used to return the maximum of the two input values.
  6. In the main function, findMax is called with int and double arguments, using type inference to determine T.
  7. The results are printed to the console using std::cout and std::endl.
  8. The main function returns 0, indicating successful program execution.