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.
📄️ Magma
To demonstrate the expressive power of the C++ language we will take a trivial example from algebra, a magma.
📄️ Functor
In this example we want to illustrate a capability of the C++ language using concepts, namely to implement the category theory concept called functor. The closest example of implementing functors in functional programming is the one in Haskell where a functor is a data type that implements a $fmap$ function.