Learn C++ · lesson 58 of 61 · about 9 minutes
Function Templates
Write one function that works for ints, doubles, strings and more.
What you'll learn
- Write a function template with typename T
- Let the compiler work out T from the arguments
- Give T explicitly when it can't be worked out
The hero's journal
Before the long walk home, the hero writes a journal. The player types the places the hero has been, like cave bridge castle, until done, and the journal lists them, then the gold found in each chest and the spells from the spell book: Places: cave, bridge, castle, Chest gold: 12, 0, 7, 20 and Spells: zap, ice, fire, frost, lightning. The places and the spells are words and the chest gold is whole numbers, but every line is written the same way, so one function template can write them all.
The same code for any type
Overloading lets you write biggest(int, int) and biggest(double, double), but the bodies are identical. A function template writes it once:
template <typename T> then T biggest(T a, T b).
T is a placeholder for a type. When you call biggest(3, 7), the compiler sees two ints and makes an int version for you.
One template, three types
#include <iostream>
#include <string>
template <typename T>
T biggest(T a, T b) {
return a > b ? a : b;
}
int main() {
std::cout << biggest(3, 7) << "\n";
std::cout << biggest(2.5, 1.5) << "\n";
std::cout << biggest(std::string("kiwi"), std::string("fig")) << "\n";
}Output
7
2.5
kiwiTemplates over containers
A template can take a whole vector of T. The only rule is that whatever T turns out to be must support what the body does: here, +=. If you mix types, like biggest(3, 2.5), the compiler can't decide what T is; writing biggest<double>(3, 2.5) tells it.
Totalling any vector
#include <iostream>
#include <string>
#include <vector>
template <typename T>
T total(const std::vector<T>& items, T start) {
for (const T& x : items) start += x;
return start;
}
int main() {
std::cout << total(std::vector<int>{1, 2, 3}, 0) << "\n";
std::cout << total(std::vector<std::string>{"ph", "oe", "be"}, std::string("")) << "\n";
}Output
6
phoebeOne journal for every list
journal takes a const std::vector<T>&, so when it's called with places the compiler works out that T is std::string, and when it's called with chests it works out that T is int. The body only sends each item to std::cout with <<, which both types support. An empty list still works: items.empty() is true, and the journal writes none yet.
Tip
Template errors can be long, because the compiler reports them from inside the template. Read the first error and look for the type it was trying to use.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.