Advanced10 min readLesson 42 of 50
What are Templates?
Templates allow writing generic code that works with any data type. The compiler generates the actual type-specific code at compile time.
Function Templates
#include <iostream>
using namespace std;
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
template <typename T>
void printArray(T arr[], int size) {
for (int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
}
int main() {
cout << maximum(3, 7) << endl; // int version: 7
cout << maximum(3.14, 2.71) << endl; // double: 3.14
cout << maximum('a', 'z') << endl; // char: z
int ints[] = {1, 2, 3, 4, 5};
double doubles[] = {1.1, 2.2, 3.3};
printArray(ints, 5);
printArray(doubles, 3);
return 0;
}
Output:
7
3.14
z
1 2 3 4 5
1.1 2.2 3.3
Class Templates
template <typename T>
class Stack {
private:
vector<T> data;
public:
void push(T val) { data.push_back(val); }
void pop() { data.pop_back(); }
T top() { return data.back(); }
bool empty() { return data.empty(); }
int size() { return data.size(); }
};
Stack<int> intStack;
Stack<string> strStack;
intStack.push(10); intStack.push(20);
cout << intStack.top() << endl; // 20
strStack.push("hello");
cout << strStack.top() << endl; // hello
Multiple Type Parameters
template <typename K, typename V>
class Pair {
public:
K key; V value;
Pair(K k, V v) : key(k), value(v) { }
void print() { cout << key << " -> " << value << endl; }
};
Pair<string, int> p1("age", 25);
Pair<int, double> p2(1, 3.14);
p1.print(); // age -> 25
p2.print(); // 1 -> 3.14
Exercise
Write a function template swap(T& a, T& b) that swaps two values of any type. Test it with int, double, and string.
Show Solution
#include <iostream>
using namespace std;
template <typename T>
void swapValues(T& a, T& b) {
T temp = a; a = b; b = temp;
}
int main() {
int x = 5, y = 10; swapValues(x, y); cout << x << " " << y << endl;
double a = 1.5, b = 2.5; swapValues(a, b); cout << a << " " << b << endl;
string s1 = "hi", s2 = "bye"; swapValues(s1, s2); cout << s1 << " " << s2 << endl;
return 0;
}
Quiz
What keyword introduces a template parameter?
- A)
generic - B)
template with typename - C)
type - D)
auto
Answer
B) template <typename T>
Summary
- Templates enable generic, type-independent code.
- Function templates work with any type:
template <typename T> T func(T a). - Class templates create generic data structures.
- The compiler instantiates the correct version at compile time.