Templates are the foundation of Generic Programming in C++. A template allows you to write a single blueprint for a function or class that works seamlessly across any data type without duplicating code.
#include <iostream>
#include <string>
// Generic template function
template <typename T>
T getMaximum(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << "Max int: " << getMaximum(15, 42) << "\n"; // Instantiates getMaximum<int>
std::cout << "Max double: " << getMaximum(3.14, 2.71) << "\n"; // Instantiates getMaximum<double>
std::cout << "Max string: " << getMaximum<std::string>("Apple", "Zebra") << "\n"; // Zebra
return 0;
}
#include <iostream>
template <typename T, int Capacity>
class FixedStack {
private:
T elements[Capacity];
int topIndex = -1;
public:
void push(const T& item) {
if (topIndex < Capacity - 1) {
elements[++topIndex] = item;
}
}
T pop() {
return elements[topIndex--];
}
};
int main() {
FixedStack<int, 10> intStack;
intStack.push(100);
std::cout << "Popped: " << intStack.pop() << "\n";
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Full and partial specialization for specific data types.
How templates power the C++ Standard Template Library.
Adding compile-time constraints to templates.