Search⌘ K
AI Features

Templates in Modules

Explore how templates are handled within C++20 modules to improve code organization and compilation efficiency. Understand the role of modules in making template definitions available during instantiation, and see practical examples that demonstrate these improvements.

We'll cover the following...

I often hear the question: How are templates exported by modules? When you instantiate a template, its definition must be available. This is the reason that template definitions are hosted in headers. Conceptually, the usage of a template has the following structure

Without modules

C++
// templateSum.h
template <typename T, typename T2>
auto sum(T fir, T2 sec) {
return fir + sec;
}
C++
// sumMain.cpp
#include <templateSum.h>
int main() {
sum(1, 1.5);
}

The main program directly includes the header templateSum.h. The call sum(1, 1.5) triggers the template instantiation. In this case, the compiler generates out of the function template sum the concrete function sum, which takes an int and a double as arguments. If you want to visualize this process, use the example on C++ Insights.

With modules

With C++20, templates can and should be in modules. Modules have a unique internal representation that is neither source code nor assembly. This representation is a kind of an abstract syntax tree (AST). Thanks to this AST, the template definition is available during template instantiation.

In the following example, I define the function template sum in module math.