Templates for Functions
Programming
This program demonstrates function templates, which allow writing generic functions that work with multiple data types without code duplication.
Implementation
#include <iostream>
// Redundant functions for different types
int findMax(int a, int b) {
return (a > b) ? a : b;
}
double findMax(double a, double b) {
return (a > b) ? a : b;
}
char findMax(char a, char b) {
return (a > b) ? a : b;
}
// Template function for all types
template <typename T>
T findMaxTemplate(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Using redundant functions
std::cout << "Redundant Functions:
";
std::cout << "Max of 10 and 20 (int): " << findMax(10, 20) << std::endl;
std::cout << "Max of 15.5 and 12.3 (double): " << findMax(15.5, 12.3) << std::endl;
std::cout << "Max of 'a' and 'z' (char): " << findMax('a', 'z') << std::endl;
// Using the template function
std::cout << "
Template Function:
";
std::cout << "Max of 10 and 20 (int): " << findMaxTemplate(10, 20) << std::endl;
std::cout << "Max of 15.5 and 12.3 (double): " << findMaxTemplate(15.5, 12.3) << std::endl;
std::cout << "Max of 'a' and 'z' (char): " << findMaxTemplate('a', 'z') << std::endl;
return 0;
} Key Concepts
- Function Overloading: Multiple functions with the same name but different parameter types
- Template:
template <typename T>defines a generic type parameter - Type Deduction: The compiler automatically deduces the template type from function arguments
- Templates eliminate code duplication and provide type safety
Benefits of Templates
- Code reuse: One function works with multiple types
- Type safety: Compile-time type checking
- Performance: No runtime overhead (code is generated at compile time)