The copy-paste problem
Say you want a function that returns the bigger of two values. You'd need one for int, one for double, one for string... all with the same code. A template lets you write it once for any type:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T biggest(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << biggest(3, 9) << "\n";
cout << biggest(2.5, 1.5) << "\n";
cout << biggest(string("apple"), string("pear")) << "\n";
cout << biggest<char>('x', 'b') << "\n";
return 0;
}Output
9 2.5 pear x
template <typename T>says: “Tstands for some type, to be decided later”.- When you call
biggest(3, 9), C++ sees twoints and creates anintversion for you. - You can also say the type yourself:
biggest<char>(...).
Think of it like this: A template is like a cookie cutter. The shape is fixed, but you can press it into any dough: chocolate, vanilla, gingerbread. The type is the dough.
Templates that work on containers
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
void printAll(const vector<T>& items) {
for (const T& item : items) {
cout << "[" << item << "] ";
}
cout << "\n";
}
int main() {
printAll(vector<int>{1, 2, 3});
printAll(vector<string>{"red", "green"});
return 0;
}Output
[1] [2] [3] [red] [green]
Remember: You've been using templates all along:
vector<int>,map<string, int>andunique_ptr<Robot>are all templates. That's where the T in STL comes from.