How do you write one function that works with int, with double and with string? With templates: the type becomes a parameter, and the compiler itself makes a version for every type that is used. This is how vector, sort and the whole STL are made.
Before you start: prior knowledge you need – inheritance, STL. How to learn: retype and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are in C++ (C++17); they have been checked to compile and give the output shown.
A function template
#include <bits/stdc++.h>
using namespace std;
template <typename T> // T is "any type"
T largest(const vector<T>& v) {
T m = v[0];
for (const T& x : v)
if (m < x) m = x; // T must support the operator <
return m;
}
template <typename T>
void printAll(const vector<T>& v) {
for (size_t i = 0; i < v.size(); i++)
cout << v[i] << (i + 1 < v.size() ? ", " : "\n");
}
int main() {
vector<int> numbers = {4, 9, 2};
vector<double> heights = {1.62, 1.75, 1.58};
vector<string> names = {"Mila", "Ana", "Teodora"};
cout << largest(numbers) << " " << largest(heights) << " " << largest(names) << "\n";
printAll(names);
return 0;
}
The program prints:
9 1.75 Teodora
Mila, Ana, Teodora
From the argument the compiler works out T by itself (int, double, string) and makes three versions of the function. The largest string is "Teodora", because strings are compared alphabetically (T comes after M and A).
A class template: your own stack
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class Stack {
vector<T> data;
public:
void push(const T& x) { data.push_back(x); }
void pop() { data.pop_back(); }
T& top() { return data.back(); }
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
};
int main() {
// checking brackets: ( [ { } ] ) – correct, ( ] – incorrect
string s;
cin >> s;
Stack<char> st; // the same class, type char
bool ok = true;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') st.push(c);
else {
char expected = c == ')' ? '(' : c == ']' ? '[' : '{';
if (st.empty() || st.top() != expected) { ok = false; break; }
st.pop();
}
}
cout << (ok && st.empty() ? "CORRECT" : "INCORRECT") << "\n";
return 0;
}
For the input ([{}]) the program prints CORRECT, and for (] it prints INCORRECT.
When you use a class template, the type is given in angle brackets: Stack<char>, Stack<int> – like vector<int>. The stack is explained in detail in the lesson Stack(SR).
Several parameters and auto
#include <bits/stdc++.h>
using namespace std;
template <typename K, typename V>
V valueOrDefault(const map<K, V>& m, const K& key, const V& defaultValue) {
auto it = m.find(key);
return it == m.end() ? defaultValue : it->second;
}
int main() {
map<string, int> points = {{"Ana", 95}, {"Iva", 80}};
cout << valueOrDefault(points, string("Ana"), 0) << " "
<< valueOrDefault(points, string("Luka"), 0) << "\n";
auto sum = [](auto a, auto b) { return a + b; }; // a "template" lambda (C++14)
cout << sum(2, 3) << " " << sum(1.5, 2.25) << " " << sum(string("ab"), string("cd")) << "\n";
return 0;
}
The program prints:
95 0
5 3.75 abcd
Notation
Meaning
template <typename T>
a template with one type (you can also write class T – it is the same)
template <typename K, typename V>
several types
template <typename T, int N>
a number can also be a parameter (e.g. array<int, 5>)
auto in a lambda
a shorter way to write simple template functions
Practice tasks
Every task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: easy
Counting the elements above the average
Write a function template aboveAverage(const vector<T>& v) that returns how many elements are strictly greater than the average. Read n integers, then m real numbers, and print both results.
Example
Input
5
1 2 3 4 5
3
1.5 2.5 10.0
Output
2 1
Hint
Compute the average as a double: the sum in a double, then divide by v.size().
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
template <typename T>
int aboveAverage(const vector<T>& v) {
double sum = 0;
for (const T& x : v) sum += x;
double average = sum / v.size();
int count = 0;
for (const T& x : v)
if (x > average) count++;
return count;
}
int main() {
int n, m;
cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
cin >> m;
vector<double> b(m);
for (double& x : b) cin >> x;
cout << aboveAverage(a) << " " << aboveAverage(b) << "\n";
return 0;
}
Common mistakes and tips
A template is written completely in the header (.h) or in the same file – the compiler must see the code to make a version for a new type.
Errors in templates are long and hard to read; look for the first line that mentions your file and line.
The type must support all operations used in the template (e.g. < for largest) – otherwise there is a compile error.
Check your knowledge
Open the quiz
Templates
1. What is T in template <typename T>?
2. How do you create an object of the class template Stack for integers?
3. Which part of the STL is NOT a template?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.