Templates
A template is a pattern for code, not code itself. You write the algorithm or class once with the type left as a parameter, and the compiler generates a separate concrete version for every type you actually use.
Detailed Explanation
You need a function that returns the larger of two values. Write it for int and you need another for double, another for std::string, another for your Money type. The bodies are identical. Before templates, C programmers solved this with preprocessor macros, which have no type checking and evaluate their arguments twice, or with void* and function pointers, which throw away type information and force indirection. Templates let you write the body once and keep full type checking.
There are two main kinds. A function template parameterises a function: template <typename T> T maximum(T a, T b). A class template parameterises a type: template <typename T> class Stack. std::vector, std::map, and std::unique_ptr are all class templates.
The word that explains everything else is instantiation. A template on its own produces no machine code. When you write maximum(3, 7), the compiler deduces T = int, substitutes it, and compiles a real function for that one type. Call it with double and it compiles a second function. Three consequences follow directly:
- Templates live in headers. The compiler needs the full body to instantiate it. A template declared in a header and defined in a
.cppgives you a linker error, because no translation unit ever generated the version you asked for. - Errors appear at instantiation, not definition. A template can be syntactically fine and still fail the moment you use it with a type that lacks the operation the body needs.
- The generated code is as fast as hand-written code. There is no runtime dispatch.
std::sortbeats C'sqsortlargely because the comparison is inlined instead of called through a function pointer.
For function templates you usually do not write the type. Template argument deduction reads it off the call. Class templates need explicit arguments up to C++14; C++17 added class template argument deduction, so std::vector v{1, 2, 3}; deduces std::vector<int>.
typename and class are interchangeable when introducing a type parameter. template <typename T> and template <class T> mean exactly the same thing. Modern code prefers typename, because T need not be a class. typename has a second, unrelated job: it tells the compiler that a dependent name like typename Container::iterator names a type rather than a static member.
Template parameters do not have to be types. A non-type template parameter is a compile-time value: template <typename T, std::size_t N> struct Array. That is how std::array<int, 16> knows its size with no runtime storage.
What it costs. Compile times grow, because the compiler recompiles the body for every type. Binary size grows, called code bloat, when many instantiations differ only slightly. And before C++20 concepts, the error messages were the worst in mainstream programming: a template body only requires that operations compile, so passing a type without operator< produced a wall of substitution text pointing deep inside library headers. That structural requirement is real duck typing, resolved at compile time: any type that supports the operations the body uses will work, whether or not it shares a base class.
Code Examples
#include <iostream>
#include <string>
// Function template: T is deduced from the arguments.
template <typename T>
const T& maximum(const T& a, const T& b) {
return a < b ? b : a; // the only requirement on T is operator<
}
// Class template with a non-type parameter: N is a compile-time value.
template <typename T, std::size_t N>
class RingBuffer {
public:
void push(const T& value) { data_[head_++ % N] = value; }
const T& operator[](std::size_t i) const { return data_[i % N]; }
private:
T data_[N]{};
std::size_t head_ = 0;
};
int main() {
std::cout << maximum(3, 7) << '\n'; // prints: 7
std::cout << maximum<std::string>("apple", "pear") << '\n'; // prints: pear
RingBuffer<int, 4> rb; // instantiates RingBuffer<int, 4> and nothing else
rb.push(10);
std::cout << rb[0] << '\n'; // prints: 10
}Header-only, because the definition must be visible where it is instantiated.
// Header-only, because the definition must be visible where it is instantiated.
#include <vector>
#include <numeric>
template <typename Container>
auto total(const Container& c) {
// typename says Container::value_type is a type, not a static member.
using Value = typename Container::value_type;
return std::accumulate(c.begin(), c.end(), Value{});
}
// total(std::vector<int>{1,2,3}) -> 6
// total(std::vector<double>{0.5, 0.25}) -> 0.75, a second instantiationCommon Gotchas
Splitting a template across header and source breaks linking
the definition must be visible at the point of instantiation. Put the body in the header, or add an explicit instantiation such as `template class Stack<int>;` in the `.cpp` if you truly want to limit the set of types.
A template is only checked when instantiated
code paths you never call are never compiled, so a bug in a rarely used branch hides until someone uses that type. Add a unit test per instantiation, or constrain the template with a C++20 concept.
Every instantiation is separate code
instantiating a large class template over twenty types multiplies the object code. Hoist type-independent logic into a non-template base or a plain function so it is compiled once.
`typename` and `class` are the same in a parameter list
the choice is style. `typename` also has a separate meaning for dependent type names, which is why it reads more consistently.