Site icon Afzal Badshah, PhD

C++ Templates and Standard Template Library (STL): A Complete Beginner-Friendly Tutorial

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:

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:

6. Why Templates Matter

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:

  1. Containers — store collections of data: vector<T>, list<T>, stack<T>, queue<T>, map<K,V>
  2. Algorithms — operate on containers (search, sort, count): sort(), find(), count()
  3. 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.
}

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
}

10. Practice Questions

  1. Write a function template minValue(T a, T b) that returns the smaller of two values. Test it with int, double, and char.
  2. Create a class template Storage<T> with a private array of size 5, a set(int index, T value) method, and a get(int index) method. Test it with int and string.
  3. Create a vector<string>, add five city names, and print them using a range-based for loop.
  4. Sort a vector<double> containing {3.5, 1.2, 4.8, 2.1} and print the sorted result.
  5. Create a multi-type Calculator<int, double> and test add() and subtract() with mixed types.
Exit mobile version