Templates write the code once for many types in C++ by turning a type into a parameter. A function template is a blueprint that the compiler fills in for each type that you use it with, and a class template is a blueprint for a whole family of classes. The standard library is built almost entirely this way, which is why a single std::vector works with strings, with integers and with your own types.
This is the first lesson in the Templates and Modern C++ module, and the next lesson in this module is about "What Do auto and range-based for Simplify?".
A function template
A function template declares its type parameters with the template keyword before the function.
#include <iostream>
#include <string>
template <typename T>
T maximum(const T& left, const T& right) {
return (left > right) ? left : right;
}
int main() {
std::cout << "int: " << maximum(4, 9) << '\n';
std::cout << "double: " << maximum(2.5, 1.5) << '\n';
std::cout << "string: " << maximum(std::string("abc"), std::string("abd")) << '\n';
return 0;
}The output shows three instantiations of the same code.
int: 9
double: 2.5
string: abdOne definition produced three separate functions. The compiler generates them as it needs them, which is why the standard library's headers can offer the algorithms for every type without the library having to know about any of them.
Template parameters
There are two kinds. A type parameter is written typename T and it stands for a type. A non-type parameter is a compile-time constant, such as an int or an enumeration value, and it can be used in the signature.
#include <array>
#include <iostream>
#include <string>
template <typename T, std::size_t N>
struct Buffer {
std::array<T, N> items;
T first() const { return items.front(); }
T last() const { return items.back(); }
};
template <int Scale>
int scaled(int value) {
return value * Scale;
}
int main() {
Buffer<std::string, 3> names{{"a", "b", "c"}};
std::cout << "first: " << names.first() << '\n';
std::cout << "last: " << names.last() << '\n';
std::cout << "scaled: " << scaled<10>(7) << '\n';
return 0;
}The output shows the fixed size used as a compile-time constant and the non-type parameter supplied explicitly.
first: a
last: c
scaled: 70And a non-type parameter has to be a constant expression. That is what allows the compiler to size the array at compile time.
A class template
A class template is a blueprint for a family of classes, and the type arguments follow the class name when you use it.
#include <iostream>
#include <string>
#include <vector>
template <typename T>
class Stack {
public:
void push(const T& value) {
items_.push_back(value);
}
T pop() {
T value = items_.back();
items_.pop_back();
return value;
}
bool empty() const { return items_.empty(); }
std::size_t size() const { return items_.size(); }
private:
std::vector<T> items_;
};
int main() {
Stack<int> numbers;
numbers.push(1);
numbers.push(2);
Stack<std::string> words;
words.push("hello");
std::cout << "numbers size: " << numbers.size() << '\n';
std::cout << "words size: " << words.size() << '\n';
std::cout << "popped: " << numbers.pop() << '\n';
return 0;
}The output shows the two instantiations behaving independently.
numbers size: 2
words size: 1
popped: 2Templates on the standard library
Almost everything in the standard library is a template, which is why it works with your own types.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Measurement {
std::string label;
double value;
};
int main() {
std::vector<Measurement> readings = {
{"oil", 42.0}, {"coolant", 91.0}, {"battery", 12.0}
};
std::sort(readings.begin(), readings.end(),
[](const Measurement& left, const Measurement& right) {
return left.value > right.value;
});
for (const Measurement& reading : readings) {
std::cout << reading.label << '=' << reading.value << ' ';
}
std::cout << '\n';
return 0;
}The output shows the custom type sorted by the standard algorithm.
coolant=91 oil=42 battery=12Template argument deduction
The compiler can usually work out the template arguments from the call, which saves a lot of the typing.
#include <iostream>
#include <string>
template <typename T>
T pick(const T& left, const T& right) {
return left > right ? left : right;
}
int main() {
std::cout << pick(4, 9) << '\n';
std::cout << pick(std::string("abc"), std::string("abcdef")) << '\n';
// Explicit arguments are needed when deduction cannot decide.
std::cout << pick<double>(1.5, 2.5) << '\n';
return 0;
}The output shows the deduced calls and the explicit one.
9
abcdef
2.5And the deduction fails when the arguments do not determine the type, which is why the explicit template arguments exist.
What templates cost
Templates are not free. The compile times grow, because every instantiation is a separate function that the compiler has to analyse, and a library with heavy template use can take a long time to compile. The error messages get long, because a mistake inside a template produces a diagnostic that mentions the template, the argument type and the instantiation point, and that can run to dozens of lines. And the code is bigger, because each instantiation is a separate copy, so a template that is used with fifty types is fifty functions.
The trade is worth it for the code that is genuinely generic. It is not worth it for a function that is used with one type, where an ordinary function or an overload would be simpler and clearer.
Common template mistakes
- Forgetting the
typenamein a dependent expression, which the older compilers reject. - Returning the type of a parameter as an
auto, which copies instead of moving. - Taking a parameter by value when a const reference would do, which copies the argument.
- Putting the templates in a header without the
inlineor thetemplate<>, which cause the duplicate symbol errors at link time. - Assuming that the deduction will work in a call with the mixed types, such as
pick(1, 2.5), which fails to deduce.
Quick reference
- A function template is written as
template <typename T>before the signature. - The arguments of a class template are supplied after the class name, such as
Stack<int>. - The non-type parameters are the compile-time constants, and they may appear in the signature.
- The compiler deduces the template arguments from the call where it can.
- The templates are instantiated per type, which increases the code size and the compile time.
- You declare the templates in a header, and you mark the free functions as inline.
Try it yourself: write a template function that returns the larger of two values, and call it with the integers, the doubles and the strings. Next, write a template class that holds a fixed number of values of any type and that reports its largest one. Then write a function that takes two template arguments and that fails to deduce when they differ, and fix it with the explicit template arguments.