Templates in C++
Templates in C++ allow you to write generic and reusable code.
You can define a function or class that works with any data type,
and the compiler will generate the appropriate code based on the
data types you use.
1. Function Templates
Function templates allow a function to work with different data
types without rewriting the entire code.
Syntax:
template <typename T>
T functionName(T arg1, T arg2) {
// Code here
}
Example: Function to find the maximum of two numbers
#include <iostream>
using namespace std;
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << "Max of 4 and 7 is: " << findMax(4, 7) << endl;
cout << "Max of 3.5 and 2.1 is: " << findMax(3.5, 2.1) << endl;
cout << "Max of 'a' and 'z' is: " << findMax('a', 'z') << endl;
return 0;
}
2. Class Templates
Class templates help create generic classes that can handle
multiple data types.
Syntax:
template <class T>
class ClassName {
T data;
public:
ClassName(T val) {
data = val;
}
void display() {
cout << "Value: " << data << endl;
}
};
Example: Class to store and display any data type
#include <iostream>
using namespace std;
template <class T>
class Box {
T value;
public:
Box(T val) {
value = val;
}
void show() {
cout << "Value is: " << value << endl;
}
};
int main() {
Box<int> intBox(10);
Box<string> strBox("Hello Template");
intBox.show();
strBox.show();
return 0;
}
3. Standard Template Library (STL)
STL is a collection of pre-written generic classes and functions
for handling data structures and algorithms.
Major STL Components:
- Containers → Store data (e.g., vector, list, map)
- Algorithms → Functions (e.g., sort(), count(), find())
- Iterators → Pointers to elements in containers
Example: vector - dynamic array
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3};
nums.push_back(4);
for (int i : nums) {
cout << i << " ";
}
return 0;
}
Example: map - key-value pairs
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> age;
age["Alice"] = 23;
age["Bob"] = 30;
for (auto p : age) {
cout << p.first << ": " << p.second << endl;
}
return 0;
}
Example: STL Algorithms
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 2, 9, 1};
sort(v.begin(), v.end());
cout << "Sorted: ";
for (int x : v) cout << x << " ";
cout << "\nMax: " << *max_element(v.begin(), v.end());
return 0;
}
Summary
Function Template → Generic function for multiple data types
Class Template → Generic class for multiple data types
STL → Library with ready-made generic structures