// Without templates: need separate overloads per type
int maxVal(int a, int b) { return a > b ? a : b; }
double maxVal(double a, double b) { return a > b ? a : b; }
// With a template: one version works for all comparable types
template<typename T>
T maxVal(T a, T b) {
return a > b ? a : b;
}
cout << maxVal(3, 7); // 7 (T=int)
cout << maxVal(3.14, 2.71); // 3.14 (T=double)
cout << maxVal('a', 'z'); // 'z' (T=char)
template<typename T, typename U>
void printPair(T a, U b) {
cout << a << " and " << b;
}
Write a generic clamp<T>(T val, T lo, T hi) that works for any comparable type.
Also write sumVector<T>(vector<T> v) that returns the sum for any numeric type.
Click "Run" to execute your code.