Templates Introduction
The problem templates solve
without_templates.cpp
#include <string>
int maxInt(int a, int b) {
return (a > b) ? a : b;
}
double maxDouble(double a, double b) {
return (a > b) ? a : b;
}
std::string maxString(std::string a, std::string b) {
return (a > b) ? a : b;
}
// ...and one more overload for every new type you need.with_templates.cpp
#include <iostream>
#include <string>
template <typename T>
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << maxValue(3, 5) << std::endl; // int
std::cout << maxValue(2.5, 1.1) << std::endl; // double
std::cout << maxValue(std::string("cat"),
std::string("dog")) << std::endl; // string
return 0;
}Compile-time, not runtime
Templates vs. function overloading
It's worth being clear about how these two features differ, since they solve related problems in different ways.
Aspect | Function Overloading | Templates |
|---|---|---|
Code written | One version per type, by hand | One generic version, compiler generates the rest |
Adding a new type | Requires writing a new overload | Works automatically if the type supports the operations used |
Behavior per type | Can differ completely between overloads | Same logic for every type (unless specialized) |
Resolved | Compile time (best match chosen) | Compile time (instantiated per type used) |
What's ahead
Function templates — generic functions like the
maxValueexample above.Class templates — generic classes and containers, like a
Box<T>you design yourself.Template specialization — providing a custom implementation for one specific type.
Variadic templates — templates that accept any number of type parameters.
Concepts (C++20) — constraining what types a template will accept, with clear error messages.