1. Introduction – Why Templates?
Imagine running a grocery shop. You use different delivery boxes for apples, oranges, and eggs. But using a separate box for every item leads to complexity. Instead, one general-purpose box that can deliver any item is more efficient.
Templates in C++ serve the same purpose: they allow you to write a single piece of code that works for multiple data types, instead of writing separate versions for int, double, string, and so on.
Templates enable generic programming — the compiler generates functions or classes for different data types automatically, so you write the logic once and reuse it everywhere.
2. What Are Templates?
A template is a generic blueprint that allows functions or classes to operate with different data types without rewriting the same code.
Think of T as a placeholder. When you call the function or create an object, the compiler replaces T with the actual type you use (int, double, string, etc.).
Syntax:
template <typename T> // T is now a placeholder for any type
You can also write template <class T> — both typename and class mean the same thing here.
3. Function Templates
Function templates let you avoid writing the same function multiple times for different data types.
Problem (Traditional Approach): You need separate functions for each type:
int maxInt(int a, int b) { return (a > b) ? a : b; }
double maxDouble(double a, double b) { return (a > b) ? a : b; }
The logic is identical — only the types differ. This is repetitive and hard to maintain.
Solution (Function Template): Write it once with a placeholder type T:
template <typename T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
Now myMax(3, 7) works for int, myMax(2.5, 3.1) works for double, and so on. The compiler automatically creates the right version based on the types you pass.
Complete Example – add() Function Template:
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(3, 4) << endl; // Output: 7 (int + int)
cout << add(2.5, 3.1) << endl; // Output: 5.6 (double + double)
cout << add<string>("Hello ", "World") << endl; // Output: Hello World
}
Key points:
- When both arguments are the same type, the compiler deduces
Tautomatically. - For
string, we writeadd<string>(...)to explicitly tell the compiler whatTis, because string literals areconst char*by default, notstring.
4. Class Templates (Single Type)
Class templates generalize classes so they can store or operate on values of any type.
Problem (Without Templates): You write a separate class for each type:
class IntBox { int value; };
class FloatBox { float value; };
Solution (Class Template): One class handles all types:
template <typename T>
class Box {
private:
T item;
public:
void set(T value) { item = value; }
T get() const { return item; }
};
Usage:
Box<int> b1;
b1.set(100);
cout << b1.get() << endl; // Output: 100
Box<string> b2;
b2.set("Apples");
cout << b2.get() << endl; // Output: Apples
Complete Example – Single-Type Calculator:
Here both num1 and num2 must be the same type:
#include <iostream>
using namespace std;
template <class T>
class Calculator {
private:
T num1, num2;
public:
Calculator(T a, T b) : num1(a), num2(b) {}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
};
int main() {
Calculator<int> obj1(10, 5);
cout << obj1.add() << endl; // Output: 15
cout << obj1.subtract() << endl; // Output: 5
Calculator<double> obj2(10.5, 2.2);
cout << obj2.add() << endl; // Output: 12.7
cout << obj2.subtract() << endl; // Output: 8.3
}
Limitation: With Calculator<int>, if you pass 10.5 as an argument, the decimal part is silently truncated to 10. You cannot mix int and double in one object. The next section solves this.
5. Multi-Type Class Templates
Sometimes you need a class where the two parameters can be different types — for example, adding an int and a double. C++ lets you use more than one type parameter.
Syntax:
template <class T1, class T2>
Now T1 and T2 are independent placeholders. Each can be a different type.
Complete Example – Multi-Type Calculator:
#include <iostream>
using namespace std;
template <class T1, class T2>
class Calculator {
private:
T1 num1;
T2 num2;
public:
Calculator(T1 a, T2 b) : num1(a), num2(b) {}
auto add() { return num1 + num2; } // C++14: return type deduced
auto subtract() { return num1 - num2; }
};
int main() {
Calculator<int, int> obj1(10, 5);
Calculator<double, double> obj2(10.5, 2.2);
Calculator<int, double> obj3(10, 2.5); // mixed types!
cout << obj1.add() << endl; // Output: 15 (int)
cout << obj2.add() << endl; // Output: 12.7 (double)
cout << obj3.add() << endl; // Output: 12.5 (double — int promoted)
cout << obj3.subtract() << endl; // Output: 7.5
}
How it works:
Calculator<int, int>— both parameters areint, soadd()returnsint.Calculator<double, double>— both aredouble, soadd()returnsdouble.Calculator<int, double>— mixed types. When C++ adds anintand adouble, it automatically promotes theinttodouble, so the result isdouble.- The
autoreturn type (C++14 feature) lets the compiler figure out the correct return type automatically.
6. Why Templates Matter
- Reusable code: Write once, use for any type — no copy-pasting functions or classes for every data type.
- Type safety: The compiler checks types at compile time, catching errors early.
- Performance: The compiler generates optimized, type-specific code for each type used — no runtime overhead.
- Foundation of STL: The entire Standard Template Library (covered next) is built using templates.
7. Introduction to STL (Standard Template Library)
In real-world applications, programmers constantly need data structures like lists, maps, stacks, and sorting algorithms. Writing these from scratch every time is time-consuming and error-prone. The STL provides these tools in a reusable and optimized form.
Definition:
STL (Standard Template Library) is a collection of template-based data structures, algorithms, and iterators that allow efficient storage, processing, and traversal of data in C++.
Three major components of STL:
- Containers — store collections of data:
vector<T>,list<T>,stack<T>,queue<T>,map<K,V> - Algorithms — operate on containers (search, sort, count):
sort(),find(),count() - Iterators — generic pointers that traverse containers:
begin(),end()
8. STL Containers – Examples
Example 1: vector<int>
A vector is a dynamic array that grows automatically as you add elements.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
for (int x : numbers)
cout << x << " "; // Output: 10 20 30
}
Example 2: pair<T1, T2>
A pair holds exactly two values, possibly of different types. It is useful for storing related data together (like a name and age).
#include <iostream>
#include <utility>
using namespace std;
int main() {
pair<string, int> student;
student.first = "Ali";
student.second = 22;
cout << student.first << " is "
<< student.second << " years old.";
// Output: Ali is 22 years old.
}
- Access the first value with
.firstand the second with.second. pairis defined in the<utility>header.
9. STL Algorithms – sort() Example
STL algorithms work on containers through iterators. The most commonly used algorithm is sort().
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> data = {4, 1, 9, 2};
sort(data.begin(), data.end()); // sorts in ascending order
for (int x : data)
cout << x << " "; // Output: 1 2 4 9
}
data.begin()returns an iterator to the first element.data.end()returns an iterator past the last element.sort()arranges elements in ascending order by default.- To sort in descending order, use:
sort(data.begin(), data.end(), greater<int>());
10. Practice Questions
- Write a function template
minValue(T a, T b)that returns the smaller of two values. Test it withint,double, andchar. - Create a class template
Storage<T>with a private array of size 5, aset(int index, T value)method, and aget(int index)method. Test it withintandstring. - Create a
vector<string>, add five city names, and print them using a range-based for loop. - Sort a
vector<double>containing{3.5, 1.2, 4.8, 2.1}and print the sorted result. - Create a multi-type
Calculator<int, double>and testadd()andsubtract()with mixed types.

