🧩 Lesson 7: Templates (Generic Programming)
⏱️ Estimated time: 25 minutes | Difficulty: Advanced
Type Flexibility
Templates allow you to write functions and classes that work with any data type, making your code extremely flexible and reusable.
What Are Templates?
Templates let you write generic code that works with any data type. Write once, use with int, double, string, or any type!
Function Templates
#include <iostream>
using namespace std;
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << getMax(10, 20) << endl; // 20 (int)
cout << getMax(3.14, 2.71) << endl; // 3.14 (double)
cout << getMax('a', 'z') << endl; // z (char)
return 0;
}
Class Templates
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T getValue() { return value; }
void display() { cout << "Box: " << value << endl; }
};
int main() {
Box<int> intBox(42);
Box<string> strBox("Hello");
Box<double> dblBox(3.14);
intBox.display(); // Box: 42
strBox.display(); // Box: Hello
dblBox.display(); // Box: 3.14
return 0;
}
Multiple Template Parameters
template <typename K, typename V>
class Pair {
K key;
V value;
public:
Pair(K k, V v) : key(k), value(v) {}
void display() {
cout << key << ": " << value << endl;
}
};
Pair<string, int> age("Alice", 25);
Pair<int, double> score(1, 95.5);
age.display(); // Alice: 25
score.display(); // 1: 95.5