Skip to main content

Templates

Generic programming in C++ is based on what we call monomorphization, a term adopted from the Rust community.

Monomorphization is a simple process whereby generic classes or functions, i.e. templates, are implemented at compile-time for each specific parameterization by literal substitution of the template parameters with the given types and values.

Monomorphization is one of three possible implementations of generics in programming languages, the others being reification and type erasure. The major disadvantage of this implementation is that it does not allow the creation of new data types at runtime. However, compared to the other two, monomorphization has the advantage of producing better optimized compiled code and does not suffer from the same limitations.

In this section, we'll explore how we can express highly abstract concepts using C++ templates and how we can apply constraints on them using C++20's concepts as compile-time predicates.