Notes
๐ง Understanding C++ Templates โ Core Concept of the STL
๐ฏ Objective of this Lesson
In this lesson, we will cover:
-
What are C++ Templates
-
The difference between template functions and template classes
-
Why and when to use templates
-
Real-world analogy and practical code examples
-
How templates help us write generic, reusable, and maintainable code
๐ฆ What Are Templates in C++?
Templates in C++ are a tool for generic programming that allow you to write code that works with any data type. Instead of duplicating code for each type (e.g., int, float, double), templates allow you to write it once and reuse it for all types.
๐ Problem Without Templates
Letโs say you want to write a function that adds two numbers:
int addInt(int a, int b) {
return a + b;
}
float addFloat(float a, float b) {
return a + b;
}You now have two nearly identical functions just because of different data types. Imagine writing this for double, long, short, etc. โ this quickly becomes unmanageable.
โจ Template Functions: Writing Generic Functions
๐งโโ๏ธ Analogy: The Magical Cookie Cutter
Think of templates as a magical cookie cutter. Normally, to cut cookies in different shapes (heart, star, circle), youโd need multiple cutters. But what if you had one cutter that could change shape on demand? Thatโs exactly what templates do โ adapt your code for different data types automatically.
โ Syntax of a Template Function:
template <typename T>
T add(T a, T b) {
return a + b;
}-
template <typename T>tells the compiler youโre using a generic type calledT. -
Tis a placeholder that gets replaced with the actual data type (int, float, double, etc.) when the function is called.
๐งช Example:
cout << add(5, 7); // Uses T = int
cout << add(5.4, 7.6); // Uses T = doubleโ Output:
12
13
๐ง Note: The compiler creates a new version of the function for each distinct type used.
๐งช Letโs Practice: More Template Functions
โ Add
template <typename T>
T add(T a, T b) {
return a + b;
}โ Subtract
template <typename T>
T subtract(T a, T b) {
return a - b;
}โ๏ธ Multiply
template <typename T>
T multiply(T a, T b) {
return a * b;
}โ Divide (with Zero Check)
template <typename T>
T divide(T a, T b) {
if (b == 0) {
cout << "Error: Division by zero\n";
return 0;
}
return a / b;
}๐ก You now have one set of functions that can work with any number type. This is what makes templates so powerful!
๐งฑ Template Classes: Creating Generic Data Structures
๐ฆ What Are Template Classes?
Just like functions, classes can also be written generically using templates. A template class can hold and work with any data type.
โ Syntax:
template <typename T>
class Box {
public:
T value;
void setValue(T val) { value = val; }
T getValue() { return value; }
};๐ง Why Use Template Classes?
-
Write once, use with any type (e.g., int, float, string)
-
Useful in data structures:
vector<T>,stack<T>,map<K, V>etc. -
Form the backbone of STL containers!
๐งฎ Practical Example: Template Calculator Class
๐งพ Code:
template <typename T>
class Calculator {
public:
T add(T a, T b) { return a + b; }
T subtract(T a, T b) { return a - b; }
T multiply(T a, T b) { return a * b; }
T divide(T a, T b) {
if (b == 0) {
cout << "Error: Division by zero\n";
return 0;
}
return a / b;
}
};๐งช Usage:
Calculator<int> intCalc;
cout << intCalc.add(5, 8); // Output: 13
cout << intCalc.divide(10, 2); // Output: 5
Calculator<float> floatCalc;
cout << floatCalc.add(5.2, 7.84); // Output: 13.04
cout << floatCalc.divide(10, 0); // Output: Error๐ฏ Benefits of Using Templates
| Benefit | Explanation |
|---|---|
| โ Code Reusability | Write once, use for any data type |
| โ Less Duplication | No need to rewrite for each type |
| โ Type Safety | Compiler ensures correct types at compile time |
| โ STL Foundation | Templates power containers like vector, map, set |
| โ Generic Algorithms | Sort, find, search โ all work with any container using templates |
๐ Summary
| Concept | Description |
|---|---|
| Template Function | Generic function that works with any type |
| Template Class | Generic class that can store or process any type |
typename T / class T | Declares a generic type placeholder |
| Real Use Case | STL containers (vector<T>, map<K, V>, etc.) |
| Benefit | DRY code, cleaner syntax, high flexibility |
๐ Practice Challenge
Write a template function and class for the following:
-
A function
maxValue(T a, T b)that returns the larger of two values. -
A template class
Storage<T>that holds a value and prints it.
Example:
template <typename T>
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
template <typename T>
class Storage {
T value;
public:
Storage(T val) : value(val) {}
void print() { cout << "Stored: " << value << endl; }
};