
C++ Templates and Standard Template Library (STL): A Complete Beginner-Friendly Tutorial
Imagine running a grocery shop. You use different delivery boxes for apples, oranges, and eggs etc. 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 writing a single piece of code that works for multiple data types.
Templates enable generic programming, letting the compiler generate functions or classes for different data types automatically.
What Are Templates?
Contents
- What Are Templates?
- Function Templates
- Example (Traditional Approach):
- Function Template:
- Complete Example:
- Class Templates
- Example Without Templates (Repetitive):
- Class Template:
- Usage:
- Class Template Example
- 6. Why Templates Matter
- Introduction to STL (Standard Template Library)
- Containers:
- Algorithms:
- Iterators:
- STL Example: vector
- STL Example: pair<T1,T2>
- STL Algorithm Example: sort()
- Practice Questions
- Share this:
- Like this:
- Related
Template help you write code that can automatically adjust to different data types, making your programs cleaner, shorter, and more efficient.
A template in C++ is a generic blueprint that allows functions or classes
to operate with different data types without rewriting the same code.
In code:
template <typename T>
This introduces T as a placeholder type.
Function Templates
Function templates help avoid writing the same function multiple times for different data types.
Example (Traditional Approach):
int maxInt(int a, int b);
double maxDouble(double a, double b);
Function Template:
template <typename T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
The compiler automatically creates versions of this function based on the types used.
Complete Example:
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(3, 4) << endl;
cout << add(2.5, 3.1) << endl;
cout << add<string>("Hello ", "World") << endl;
}
Class Templates
Class templates generalize classes to store or operate on values of any type.
Example Without Templates (Repetitive):
class IntBox { int value; };
class FloatBox { float value; };
Class Template:
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);
Box<string> b2;
b2.set("Apples");
Class Template Example
#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;
Calculator<int> obj2(10.5, 2.2);
cout << obj2.add() << endl;
}
6. Why Templates Matter
- Reusable code: Write once, use for any type.
- Type safety: Compiler handles type correctness.
- Performance: Optimized code generated per type.
- Foundation of STL: The Standard Template Library uses templates extensively.
Introduction to STL (Standard Template Library)
To manage data efficiently in real-world applications, programmers need ready-made structures such as lists, maps, stacks, and sorting functions. Writing these from scratch every time is time‑consuming and error‑prone. The Standard Template Library (STL) provides these tools in a reusable and optimized form.
Here is the student‑friendly 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++.
STL provides the following major components:
Containers:
vector<T>list<T>queue<T>stack<T>map<Key,Value>
Algorithms:
sort()find()count()
Iterators:
Generic pointers for containers.
STL Example: vector
#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 << " ";
}
STL Example: pair<T1,T2>
#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.";
}
STL Algorithm Example: sort()
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> data = {4, 1, 9, 2};
sort(data.begin(), data.end());
for (int x : data)
cout << x << " ";
}
Practice Questions
- Write a function template
minValue(). - Create a class template
Storage<T>. - Create and print a vector of strings.
- Sort a vector of doubles.