C++ Templates
What are Templates?
Templates are C++'s mechanism for generic programming. They let you write a function or class once and have the compiler generate type-specific versions automatically. This eliminates code duplication while maintaining full type safety.
- Function templates — generic functions that work with any type.
- Class templates — generic classes (like
std::vector<T>).
Function Templates
#include <iostream>
#include <string>
using namespace std;
// Function template — T is a placeholder for any type
template <typename T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
// Template with multiple type parameters
template <typename T, typename U>
void printPair(T first, U second) {
cout << first << " : " << second << endl;
}
// Template specialization — custom behaviour for a specific type
template <>
string maxOf<string>(string a, string b) {
return (a.length() > b.length()) ? a : b; // longer string wins
}
int main() {
cout << maxOf(3, 7) << endl; // 7 (int)
cout << maxOf(3.14, 2.71) << endl; // 3.14 (double)
cout << maxOf('z', 'a') << endl; // z (char)
cout << maxOf<string>("Hi", "Hello") << endl; // Hello (longer)
printPair("Name", "Alice");
printPair("Age", 30);
printPair(3.14, true);
return 0;
}
Class Templates
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
template <typename T>
class Stack {
private:
vector<T> data;
public:
void push(const T &item) {
data.push_back(item);
}
T pop() {
if (empty()) throw runtime_error("Stack is empty");
T top = data.back();
data.pop_back();
return top;
}
T& peek() {
if (empty()) throw runtime_error("Stack is empty");
return data.back();
}
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
};
int main() {
// Stack of ints
Stack<int> intStack;
intStack.push(10);
intStack.push(20);
intStack.push(30);
cout << "Top: " << intStack.peek() << endl; // 30
cout << intStack.pop() << endl; // 30
cout << intStack.pop() << endl; // 20
// Stack of strings — same class, different type
Stack<string> strStack;
strStack.push("Hello");
strStack.push("World");
cout << strStack.pop() << endl; // World
return 0;
}