Function Templates
Learn how to write generic functions using templates that work with any data type
Templates are C++'s powerful feature for writing generic code that works with any data type. Instead of duplicating code for different types, you write it once as a template.
A Simple Example
#include <iostream>
template<typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
template<typename T>
void swapValues(T& a, T& b) {
T temp{a};
a = b;
b = temp;
}
template<typename T>
void printArray(const T arr[], int size) {
std::cout << "[";
for (int i{0}; i < size; ++i) {
std::cout << arr[i];
if (i < size - 1) std::cout << ", ";
}
std::cout << "]" << "\n";
}
int main() {
std::cout << "Max of 10, 20: " << maximum(10, 20) << "\n";
std::cout << "Max of 3.5, 2.1: " << maximum(3.5, 2.1) << "\n";
std::cout << "Max of 'a', 'z': " << maximum('a', 'z') << "\n";
int x{5}, y{10};
std::cout << "Before swap: x=" << x << ", y=" << y << "\n";
swapValues(x, y);
std::cout << "After swap: x=" << x << ", y=" << y << "\n";
int numbers[]{1, 2, 3, 4, 5};
double decimals[]{1.1, 2.2, 3.3};
printArray(numbers, 5);
printArray(decimals, 3);
return 0;
}
Breaking It Down
template<typename T>
- What it does: Declares a template parameter T that represents any type
- typename vs class: Both keywords work identically for type parameters
- Use for: Creating generic functions that work with multiple types
- Remember: The compiler generates a separate function for each type used
Template Function Declaration
-
Syntax:
template<typename T> T functionName(T param) - T can appear: As return type, parameter type, or local variable type
- Benefit: Write once, compiler generates type-specific versions automatically
- Remember: Template definitions must be in header files or same file as usage
Type Inference
- What it does: Compiler deduces T from arguments automatically
-
Example:
maximum(10, 20)deduces T as int,maximum(3.5, 2.1)deduces double -
Explicit syntax: Can also write
maximum<int>(10, 20)if needed - Remember: All arguments must deduce to the same type or you need explicit specification
Template Instantiation
- What happens: Compiler generates actual code for each type used
-
Compile-time:
maximum<int>andmaximum<double>become separate functions - Zero overhead: No runtime cost, same performance as hand-written functions
- Trade-off: Increases binary size since each type gets its own function
Why This Matters
- Templates are C++'s secret weapon for code reuse - write once, use for any type.
- Instead of writing `max(int, int)`, `max(double, double)`, etc., write one template that works for all types.
- This is how the entire STL works - `vector<T>`, `sort()`, and all standard algorithms.
- Templates enable generic programming, compile-time polymorphism, and zero-overhead abstractions.
Critical Insight
Templates aren't runtime polymorphism - they're compile-time code generation! When you use maximum(10, 20) and maximum(3.5, 2.1), the compiler creates two completely different functions: maximum<int> and maximum<double>.
It's like having a cookie cutter (the template) that creates actual cookies (concrete functions) for each type you use. This means zero runtime overhead but potentially larger executable size.
Best Practices
Keep templates in headers: Unlike regular functions, template definitions must be visible where they are used. Put them in header files.
Use meaningful type parameter names: While T is common for single parameters, use descriptive names like TKey, TValue for clarity in complex templates.
Add constraints when needed: Use concepts (C++20) or static_assert to ensure T has required operations like operator< or operator+.
Prefer typename over class: Both work identically for type parameters, but typename is clearer about intent.
Common Mistakes
Linker errors: Defining templates in .cpp files causes "undefined reference" errors. Templates need definitions in headers.
Type mismatch: Calling maximum(10, 3.5) fails because int and double don't match. Use explicit type: maximum<double>(10, 3.5).
Compilation time: Heavy template use increases compilation time since each instantiation requires code generation.
Error messages: Template compilation errors can be cryptic and verbose. Read from the first error message.
Debug Challenge
This template function has a bug in the template declaration. Click the highlighted line to fix it:
Quick Quiz
- What happens when you call maximum(10, 20) with an int template?
- What is the main benefit of function templates?
- Where must template function definitions be placed?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once