C++ Code Example 4: Simple Function Template Example

In this example, the “max” function template takes two arguments of the same type “T” and returns the maximum value. The type parameter “T” can be any type that supports the greater than operator (“>”).

The main function demonstrates how the “max” function template can be used with different types of data. It creates two integer variables “x” and “y” and two floating-point variables “a” and “b”. The “max” function is called twice, once with the integers and once with the floating-point values. The output displays the maximum value of each pair of values.

Note that the type parameter “T” is inferred from the data types of the arguments passed to the function template. You can also explicitly specify the type parameter by using the angle bracket syntax.

#include <iostream>

template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int x = 10, y = 20;
    float a = 3.14, b = 2.71;
    std::cout << "max of x and y: " << max(x, y) << std::endl;
    std::cout << "max of a and b: " << max(a, b) << std::endl;
    return 0;
}