Templates
Write one function or class that works for many types.
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
T largest(const vector<T> &items) {
T best = items[0];
for (const T &x : items) {
if (best < x) {
best = x;
}
}
return best;
}
template <typename T>
class Box {
T value;
public:
explicit Box(T v) : value(v) {}
T get() const { return value; }
};
int main() {
cout << largest(vector<int>{3, 9, 4}) << "\n";
cout << largest(vector<string>{"pear", "apple", "mango"}) << "\n";
Box<double> b(8.5);
cout << b.get() << "\n";
return 0;
}Output
9 pear 8.5
The compiler writes a separate version of largest for each type you use it with. The type only needs the operations the template uses, here copying and <. Strings compare in dictionary order, so pear is the largest.
vector, map, sort and unique_ptr are all templates. That is why the angle brackets appear everywhere in C++ code.