Module 6 · Generic code
6.2Class templates
Write a type once and use it with any element type, put a fixed size into the type with a value parameter, and let the compiler work out the arguments with CTAD.
On this page
- Key terms
- In 30 seconds
- Writing a class template
- Member functions: a Grid<T>
- Values as template parameters: Vec<T, N>
- Letting the compiler work out the arguments: CTAD
- A different definition for one type: specialization
- Shorter names: alias templates
- Which one should I use?
- Under the hood
- Common pitfalls
- CTAD with mixed types
- Leaving out <T> outside the class
- A member that needs something the type lacks
- Try it yourself
Key terms
- class template
- A pattern for a type, like
template <typename T> struct Interval.Interval<int>is a type made from it. - non-type template parameter
- A template parameter that's a value instead of a type, like
std::size_t NinVec<T, N>. It must be known when you compile. - dot product
- Multiply the matching elements of two vectors and add the results. Models use it to measure how alike two vectors are.
- class template argument deduction (CTAD)
- The compiler working out a class template's arguments from the initializer, as in
std::vector v{1, 2, 3}. - specialization (
template <>) - A separate definition of a template for particular arguments. The compiler uses it instead of the general one.
- type alias (
using) - A second name for a type:
using Embedding = Vec<float, 4>;. - alias template
- A type alias with template parameters:
template <std::size_t N> using FloatVec = Vec<float, N>;. - embedding
- A fixed-size vector of floats that a model uses to stand for a word, an image or a DNA sequence.
You’ve used class templates since Module 2: std::vector<int>, std::array<int, 6>, std::unique_ptr<Node>. Each is one definition that works with any element type. Your own types have the same need. A grid of pixels and a grid of scores differ only in what each cell holds, and writing the class twice means fixing every bug twice. A class template lets you write the type once, with the element type, or even a size, left as a parameter.
In 30 seconds
template <typename T> struct Interval { T low; T high; };is a class template.Interval<int>is a type made from it.- Member functions can use
T. Defined outside the class, they repeat thetemplateline and write the class asGrid<T>::. - A template parameter can be a value:
Vec<float, 3>andVec<float, 4>are different types, so mixing them up is a compile error. - The compiler can often work out the arguments from the initializer:
std::vector v{1, 2, 3}is astd::vector<int>.
Writing a class template
Put template <typename T> in front of a struct or class, and use T for the types that vary. Members, member functions and parameters can all use it.
#include <print>
template <typename T>
struct Interval {
T low;
T high;
bool contains(T x) const { return low <= x && x <= high; }
T width() const { return high - low; }
};
int main() {
Interval<int> exon{100, 250};
Interval<double> quality{20.0, 40.0};
std::println("{} {}", exon.width(), exon.contains(180));
std::println("{} {}", quality.width(), quality.contains(12.5));
}Output
150 true 20 false
Interval on its own isn’t a type; it’s the pattern. Interval<int> is a type, made by putting int in place of T, the same way the compiler makes larger<int> from a function template in Function templates. Interval<int> and Interval<double> are two separate types that happen to come from one definition.
Member functions: a Grid<T>
A class template can have private members, constructors and member functions like any class. This Grid stores its cells in one flat vector, row after row, as in Arrays and span:
#include <cstddef>
#include <print>
#include <vector>
template <typename T>
class Grid {
public:
Grid(std::size_t rows, std::size_t cols, T fill)
: rows_{rows}, cols_{cols}, cells_(rows * cols, fill) {}
std::size_t rows() const { return rows_; }
std::size_t cols() const { return cols_; }
T& at(std::size_t row, std::size_t col);
private:
std::size_t rows_;
std::size_t cols_;
std::vector<T> cells_;
};
template <typename T>
T& Grid<T>::at(std::size_t row, std::size_t col) {
return cells_[row * cols_ + col];
}
int main() {
Grid<char> image(2, 4, '.');
image.at(0, 1) = '#';
image.at(1, 2) = '#';
for (std::size_t r = 0; r < image.rows(); ++r) {
for (std::size_t c = 0; c < image.cols(); ++c) {
std::print("{}", image.at(r, c));
}
std::println("");
}
}Output
.#.. ..#.
cells_(rows * cols, fill) makes a vector of rows * cols copies of fill. A Grid<float> of scores, or a Grid<int> of counts, uses the same code.
at is declared in the class and defined below it. Outside the class, you repeat the template <typename T> line and name the function as Grid<T>::at: at, in the class Grid<T>. Inside the class body, the plain name Grid means Grid<T>, so you don’t have to repeat <T> there.
Values as template parameters: Vec<T, N>
A template parameter can also be a value, like a size. std::array<T, N> from Arrays and span works this way: std::array<int, 6> has the 6 in its type. Here is a small fixed-size vector of the kind AI code uses everywhere, with a dot product:
#include <array>
#include <cstddef>
#include <print>
template <typename T, std::size_t N>
struct Vec {
std::array<T, N> values;
T dot(const Vec& other) const {
T total{};
for (std::size_t i = 0; i < N; ++i) {
total += values[i] * other.values[i];
}
return total;
}
};
int main() {
Vec<float, 3> query{1.0f, 2.0f, 3.0f};
Vec<float, 3> key{0.5f, 0.5f, 2.0f};
std::println("{}", query.dot(key));
}Output
7.5
std::size_t N is a non-type template parameter: N is a number, fixed when you compile. Inside the template it’s a constant, so the loop runs exactly N times and nothing stores the size at run time. T total{} starts at zero, as in mean in the previous lesson.
Inside Vec, the plain name Vec means Vec<T, N>, so dot accepts only a vector of the same element type and the same size. A size mismatch, a common bug with vectors of floats, is caught when you compile:
#include <array>
#include <cstddef>
#include <print>
template <typename T, std::size_t N>
struct Vec {
std::array<T, N> values;
T dot(const Vec& other) const {
T total{};
for (std::size_t i = 0; i < N; ++i) {
total += values[i] * other.values[i];
}
return total;
}
};
int main() {
Vec<float, 3> query{1.0f, 2.0f, 3.0f};
Vec<float, 4> key{0.5f, 0.5f, 2.0f, 1.0f};
std::println("{}", query.dot(key));
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:21:34: error: cannot convert ‘Vec<float, 4>’ to ‘const Vec<float, 3>&’
21 | std::println("{}", query.dot(key));
| ^~~
| |
| Vec<float, 4>
main.cpp:9:22: note: initializing argument 1 of ‘T Vec<T, N>::dot(const Vec<T, N>&) const [with T = float; long unsigned int N = 3]’
9 | T dot(const Vec& other) const {
| ~~~~~~~~~~~^~~~~Vec<float, 3> and Vec<float, 4> are different types, as different as int and std::string. A std::vector<float> can’t do this: its size is only known when the program runs, so a mismatch has to be checked then.
Key ideaThe value must be known when you compile
N is part of the type, so it must be a constant: Vec<float, 3>, or a constexpr variable. A size read from input or a file can’t go there; use a std::vector for that.
Letting the compiler work out the arguments: CTAD
Writing <int> every time gets repetitive when the initializer already says it. Class template argument deduction (CTAD) lets you leave the arguments out of a variable’s type, and the compiler works them out from the initializer:
#include <array>
#include <print>
#include <vector>
template <typename T>
struct Interval {
T low;
T high;
};
int main() {
std::vector lengths{150, 98, 151}; // std::vector<int>
std::array bases{'A', 'C', 'G', 'T'}; // std::array<char, 4>
Interval exon{100, 250}; // Interval<int>
Interval score{0.25, 0.75}; // Interval<double>
std::println("{} {}", lengths, bases.size());
std::println("{} {}", exon.high - exon.low, score.high - score.low);
}Output
[150, 98, 151] 4 150 0.5
std::array bases{'A', 'C', 'G', 'T'} works out both arguments: the element type from the values, and the size from how many there are. For your own types, CTAD usually works when the members or the constructor’s parameters use T. Grid image(2, 4, '.') would be a Grid<char>, because the constructor’s fill parameter has type T.
Common pitfallCTAD takes the initializer literally
std::vector names{"Ada", "Alan"} is a vector of const char*, not of std::string, because that’s what string literals give. When the deduced type isn’t the one you want, write it: std::vector<std::string> names{"Ada", "Alan"}.
A different definition for one type: specialization
Sometimes one type needs different code from the rest. A specialization is a second definition of the template for particular arguments, written with template <> and the arguments after the name. The compiler uses it whenever those arguments come up, and the general template otherwise:
#include <print>
#include <string_view>
#include <vector>
template <typename T>
struct TypeName {
static constexpr std::string_view value = "something";
};
template <>
struct TypeName<int> {
static constexpr std::string_view value = "int";
};
template <>
struct TypeName<float> {
static constexpr std::string_view value = "float";
};
template <typename T>
void describe(const std::vector<T>& values) {
std::println("{} values of type {}", values.size(), TypeName<T>::value);
}
int main() {
describe(std::vector<int>{1, 2, 3});
describe(std::vector<float>{0.5f, 0.25f});
describe(std::vector<char>{'A', 'C'});
}Output
3 values of type int 2 values of type float 2 values of type something
static makes value belong to the type itself, not to each object, so you read it as TypeName<int>::value. You’ll rarely write a specialization, but you’ll meet them: making your own type printable with std::println means specializing std::formatter, as Operators and comparisons shows, and std::vector<bool> is a specialization of std::vector with its own oddities (vector).
Shorter names: alias templates
using Name = Type; gives a type a second name, a type alias. Put a template line in front and you get an alias template: a short name with some arguments already filled in.
#include <array>
#include <cstddef>
#include <print>
template <typename T, std::size_t N>
struct Vec {
std::array<T, N> values;
};
template <std::size_t N>
using FloatVec = Vec<float, N>; // FloatVec<3> is Vec<float, 3>
using Embedding = FloatVec<4>; // one type: Vec<float, 4>
int main() {
FloatVec<3> position{1.0f, 2.0f, 3.0f};
Embedding word{0.1f, 0.2f, 0.3f, 0.4f};
std::println("{} {}", position.values, word.values);
}Output
[1, 2, 3] [0.1, 0.2, 0.3, 0.4]
An alias makes no new type. Embedding and Vec<float, 4> are the same type with two names, so you can pass one where the other is expected. An embedding is a vector of floats that a model uses to stand for something, like a word; real ones have hundreds of elements, not four.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| Class template | A container or wrapper whose code is the same for every element type. | One definition to read, test and fix. | template <typename T> class Grid |
| Non-type parameter | The size is fixed and known when you compile: 3D points, small vectors, 4×4 matrices. | No heap, no stored size, and mixing sizes is a compile error. | Vec<float, 3>, std::array<int, 6> |
std::vector<T> | The size comes from input or changes while the program runs. | The size can be anything, at the cost of a heap block. | std::vector<float> scores(n) |
| CTAD | The initializer makes the type obvious. | Less to write, and the type follows the values. | std::vector v{1, 2, 3} |
| Written arguments | The deduced type isn’t the one you want, or there’s no initializer. | You decide the type. | std::vector<std::string> names{"Ada"} |
| Alias template | You write a long template name often, with some arguments always the same. | Shorter, and one place to change it. | template <std::size_t N> using FloatVec = Vec<float, N>; |
Rule of thumb: write a class template when you’d otherwise copy a class and change only a type or a size; put the size in the type when it’s fixed, and use std::vector when it isn’t.
Under the hood
Each set of arguments makes a separate type with its own size and its own copy of the member functions. A Vec stores its elements and nothing else, because N lives in the type, not in the object. A std::vector stores a handle to a heap block instead:
#include <array>
#include <cstddef>
#include <print>
#include <vector>
template <typename T, std::size_t N>
struct Vec {
std::array<T, N> values;
};
int main() {
std::println("{} {} {}", sizeof(Vec<float, 3>), sizeof(Vec<float, 4>),
sizeof(std::vector<float>));
}Output
12 16 24
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Vec<float, 3> | [0]4 bytes | [1]4 bytes | [2]4 bytes | 12 bytes | |||||||||||||||||||||
Vec<float, 4> | [0]4 bytes | [1]4 bytes | [2]4 bytes | [3]4 bytes | 16 bytes | ||||||||||||||||||||
std::vector<float> | start8 bytes · pointer | end8 bytes · pointer | capacity end8 bytes · pointer | 24 bytes | |||||||||||||||||||||
Vec<float, 3> is 12 bytes: three 4-byte floats. Vec<float, 4> is 16 bytes: four floats. Neither stores its size. std::vector<float> is 24 bytes with GCC's standard library: three 8-byte pointers to its heap block, for the start, the end of the elements and the end of the capacity. The floats themselves are on the heap.
The Vec sizes follow from float being 4 bytes on this platform, with no padding between the elements. The 24 bytes of std::vector<float> are GCC’s standard library on 64-bit Linux; the standard fixes none of these sizes. A small Vec can live on the stack or inside another object with no heap allocation, which matters when a program handles millions of them.
The compiler also writes only the member functions you call. So a Grid<T> can have a member that needs +, and you can still make a Grid of a type without +, as long as you don’t call that member. The last pitfall below shows what happens when you do.
As with function templates, a class template’s full definition, member functions included, goes in a header, so every file that uses Grid<char> can write it. Module 8 covers headers.
Common pitfalls
CTAD with mixed types
CTAD has to find one T for every member, so values of two types can’t make an Interval:
#include <print>
template <typename T>
struct Interval {
T low;
T high;
};
int main() {
Interval range{1, 2.5};
std::println("{}", range.high - range.low);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:10:26: error: class template argument deduction failed:
10 | Interval range{1, 2.5};
| ^
compilation terminated due to -fmax-errors=1.Write Interval range{1.0, 2.5}, or name the type: Interval<double> range{1, 2.5}. With the type written, there’s nothing to deduce, and 1 becomes 1.0.
Leaving out <T> outside the class
A member function defined outside its class template needs both the template line and Grid<T>::. Grid on its own names the template, not a class, so Grid::at is an error:
#include <cstddef>
#include <vector>
template <typename T>
class Grid {
public:
T& at(std::size_t row, std::size_t col);
private:
std::size_t cols_ = 0;
std::vector<T> cells_;
};
template <typename T>
T& Grid::at(std::size_t row, std::size_t col) {
return cells_[row * cols_ + col];
}
int main() {}The compiler rejects this
main.cpp:15:4: error: ‘template<class T> class Grid’ used without template arguments
15 | T& Grid::at(std::size_t row, std::size_t col) {
| ^~~~
compilation terminated due to -fmax-errors=1.The fix is T& Grid<T>::at(std::size_t row, std::size_t col).
A member that needs something the type lacks
This Column has a sum member that uses +=. A Column<Read> is fine until you call sum, because only then does the compiler write Column<Read>::sum:
#include <print>
#include <string>
#include <vector>
template <typename T>
struct Column {
std::vector<T> values;
T sum() const {
T total{};
for (const T& v : values) {
total += v;
}
return total;
}
};
struct Read {
std::string id;
};
int main() {
Column<Read> reads;
reads.values.push_back(Read{"r1"});
std::println("{}", reads.values.size()); // fine
std::println("{}", reads.sum().id); // needs += for Read
}The compiler rejects this
main.cpp: In instantiation of ‘T Column<T>::sum() const [with T = Read]’:
main.cpp:26:33: required from here
26 | std::println("{}", reads.sum().id); // needs += for Read
| ~~~~~~~~~^~
main.cpp:12:19: error: no match for ‘operator+=’ (operand types are ‘Read’ and ‘const Read’)
12 | total += v;
| ~~~~~~^~~~The error points inside sum, with “required from here” at your call, as in Function templates. Either don’t call sum for that type, or give it what sum needs. Concepts shows how a template can state its requirements so this error is shorter and points at the call.
Try it yourself
Try it yourself
CharCounter counts how often each char is added. Turn it into a class template Counter<T>, then use a Counter<char> to count the bases of "GATAGATA" and a Counter<std::string> to count its 2-letter pieces (k-mers), from dna.substr(i, 2). The program should print A: 4 and GA: 2.
#include <map>
#include <print>
#include <string>
class CharCounter {
public:
void add(char item) { ++counts_[item]; }
int count(char item) const {
return counts_.contains(item) ? counts_.at(item) : 0;
}
private:
std::map<char, int> counts_;
};
int main() {
std::string dna = "GATAGATA";
CharCounter bases;
for (char b : dna) {
bases.add(b);
}
std::println("A: {}", bases.count('A'));
}Expected output
A: 4 GA: 2
Show a hint
Put template <typename T> above the class, rename it Counter, and replace char with T in add, count and the map. Take the items as const T& so strings aren't copied.
Show a solution
#include <cstddef>
#include <map>
#include <print>
#include <string>
template <typename T>
class Counter {
public:
void add(const T& item) { ++counts_[item]; }
int count(const T& item) const {
return counts_.contains(item) ? counts_.at(item) : 0;
}
private:
std::map<T, int> counts_;
};
int main() {
std::string dna = "GATAGATA";
Counter<char> bases;
for (char b : dna) {
bases.add(b);
}
Counter<std::string> kmers;
for (std::size_t i = 0; i + 2 <= dna.size(); ++i) {
kmers.add(dna.substr(i, 2));
}
std::println("A: {}", bases.count('A'));
std::println("GA: {}", kmers.count("GA"));
}Counter<char> and Counter<std::string> are two types made from one definition. Their member functions aren't templates of their own: in Counter<std::string>, count takes a const std::string&, so the literal GA converts to a std::string with no deduction involved, unlike count_equal in the previous lesson.
Saved in this browser only.