AI Features

Templates in Modules

Explore templates with and without modules.

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

// templateSum.h
template <typename T, typename T2>
auto sum(T fir, T2 sec) {
return fir + sec;
}
// 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.

Ask