What is monomorphisation with context to C++?

Monomorphization means generating specialized versions of generic functions. If I write a function that extracts the first element of any pair:

fn first<A, B>(pair: (A, B)) -> A {
    let (a, b) = pair;
    return a;

and then I call this function twice:

first((1, 2));
first(("a", "b"));

The compiler will generate two versions of first(), one specialized to pairs of integers and one specialized to pairs of strings.

The name derives from the programming language term “polymorphism” — meaning one function that can deal with many types of data. Monomorphization is the conversion from polymorphic to monomorphic code.

Leave a Comment