Programming Search⌘K

Conceptcore

Templates and generics

Also called C++ templates, Java generics, C# generics, template instantiation, monomorphization, reified generics, erased generics, GC shape stenciling, how generics are compiled.

C++ templates make a copy of the code for each type, Java generics are checked and then erased, and C#, Go and Rust each keep a different part of the type at run time.

Applies to
core-languages

Idea

Many languages let one function or class work for many types. They all check the generic code, but they differ in what they make from it. C++ makes a separate copy of a template for each type that uses it. Java checks the types and then erases them, so one copy of the code works for every type. C#, Go and Rust each take a way between these two. The choice decides what the program can ask about a type when it runs, how fast the code is, and how large the program becomes.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        List<Integer> nums = new ArrayList<>();
        // One class for both lists: the type argument is erased.
        System.out.println(names.getClass() == nums.getClass());
        System.out.println(names.getClass().getName());
    }
}
Output
true
java.util.ArrayList

In Java, List<String> and List<Integer> are different types to the compiler, but the program has one class for both. In C++, std::vector<std::string> and std::vector<int> are two classes with two copies of the code.

How it works

C++ templates make code for each type. "A template is a C++ entity that defines" a family of classes, functions or variables1. The template arguments "are substituted for the template parameters to obtain a specialization of the template, that is, a specific type or a specific function lvalue"1. When the program uses a specialization, "the template is instantiated (the code for it is actually compiled)"1. The compiler checks the body of a template for each type that it makes. A template that calls x.size() compiles for any type that has size, and the error for a type without it appears when the template is instantiated. Concepts let the template state its needs, so "Violations of constraints are detected at compile time, early in the template instantiation process"2.

Java generics are checked and then erased. Java uses the type arguments to check the program: generics give "Stronger type checks at compile time"3. Then the compiler removes them. It applies type erasure to "Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded"4 and to "Insert type casts if necessary to preserve type safety"4. The compiled code "contains only ordinary classes, interfaces, and methods"4, so all the parameterized types of one generic class share one class. See type erasure.

C# generics are kept in the runtime. In .NET, a compiled generic type "contains metadata that identifies it as having type parameters"5. The runtime makes code for each value type: "Specialized generic types are created one time for each unique value type that is used as a parameter."5 For reference types, it shares one copy: "the runtime reuses the previously created specialized version of the generic type. This is possible because all references are the same size."5 The program can ask for the type argument when it runs.

Rust makes a copy for each type. "Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled."6 "Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics."6 For one shared copy of the code, Rust has trait objects. "A trait object is an opaque value of another type that implements a set of traits."7 A pointer to it includes "a virtual method table, often just called a vtable"7.

Go shares code by shape. The Go design generates "a single chunk of assembly for each unique GC shape used by any instantiation"8. The GC shape of a type "means how that type appears to the allocator / garbage collector. It is determined by its size, its required alignment, and which parts of the type contain a pointer."8 Each chunk takes a dictionary that describes the real type arguments. Types with the same shape, such as all pointer types, share one copy of the code.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptDoes not applyJavaScript has no type parameters, so there is no generic code to compile.
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin generics on the JVM are erased, as in Java, and an inline function can have a reified type parameter. No example file exists because kotlinc is not installed.
SQLDoes not applyA query has no type parameters.
BashDoes not applyBash has no types for its values.
PowerShellDoes not applyA PowerShell script can use the generic types of .NET, but it cannot declare its own generic functions or types. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no types of values.
CSSDoes not applyCSS has no types in this sense.
Regular expressionsDoes not applyA regular expression has no types.
Language Verdict Mechanism
Python native type parameters for static checkers only; the program runs one copy of the code
JavaScript n/a the language has no type parameters
TypeScript native generics checked by the compiler and then removed; the JavaScript output has no types
Java native generics checked by the compiler and then erased to the bound or Object
Kotlin native erased on the JVM, as in Java; reified type parameters in inline functions
C# native generics kept in the runtime; code for each value type, and one shared copy for reference types
Go native one copy of the code for each GC shape, with a dictionary of the type arguments
Rust native monomorphization: a copy for each type; dyn Trait for one shared copy
C idiom macros that make code for each type, or void * with one copy
C++ native templates instantiated for each set of template arguments
Bash n/a the language has no types
PowerShell n/a a script cannot declare its own generic functions or types
SQL n/a a query has no type parameters
Regex n/a a pattern has no types
HTML n/a HTML has no types
CSS n/a CSS has no types of this kind

C++ and Rust make code for each type, so the code is fast and the program is larger. Java, Kotlin, TypeScript and Python keep one copy, so the program cannot ask for a type argument when it runs. C# and Go share some code and copy some.

The example files show what each way keeps. Python and TypeScript show that the type arguments are not checked when the program runs. Java shows the casts that erasure adds, and that new T() is not allowed. C# shows that typeof(T) gives the real type argument. Go shows a generic function that works for int and string. Rust shows a generic function and a dyn Trait version. C shows a macro that makes a function for each type. C++ shows a template that compiles only for the types that it is used with.

PythonGitHub
class Box[T]:
    def __init__(self, item: T) -> None:
        self.item = item


a = Box[int](1)
b = Box[str]("x")
print(type(a) is type(b), type(a).__name__)

c = Box[int]("not an int")  # a type checker reports this line
print(c.item)
Output
True Box
not an int
  • Verdict: native. Box[int] and Box[str] are one class when the program runs, and the type argument is not checked. Only a static type checker uses it.
#include <array>
#include <iostream>
#include <string>
#include <vector>

// The body is checked for each type that uses the template.
template <typename C>
std::size_t twice_size(const C& c) {
    return 2 * c.size();
}

// N is a non-type template parameter.
template <typename T, std::size_t N>
T sum(const std::array<T, N>& a) {
    T total{};
    for (const T& x : a) {
        total += x;
    }
    return total;
}

int main() {
    std::cout << twice_size(std::string("abc")) << " " << twice_size(std::vector<int>{1, 2}) << "\n";
    std::cout << sum(std::array<int, 4>{1, 2, 3, 4}) << "\n";
    // twice_size(5) would not compile: int has no size().
}
Output
6 4
10
  • Verdict: native. The compiler makes twice_size<std::string> and twice_size<std::vector<int>>, and it checks c.size() for each of them. A call with an int fails inside the template. std::array<int, 4> has a number as a template argument.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class Main {
    // new T() is not allowed, so the caller passes a factory.
    static <T> List<T> fill(int n, Supplier<T> make) {
        List<T> out = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            out.add(make.get());
        }
        return out;
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        System.out.println(fill(2, StringBuilder::new).size());

        // The cast to List<String> is not checked when the program runs.
        Object o = List.of(1, 2);
        List<String> strings = (List<String>) o;
        System.out.println(strings.size());
        try {
            String s = strings.get(0); // the cast that erasure inserts fails here
            System.out.println(s);
        } catch (ClassCastException e) {
            System.out.println("ClassCastException");
        }
    }
}
Output
2
2
ClassCastException
  • Verdict: native. The compiler checks List<String> and then erases it to List. The cast (List<String>) o cannot check the item type, so the error comes from the cast to String that the compiler inserts at get.
#include <stdio.h>

/* The macro writes one function for each type. */
#define DEFINE_MAX(T)            \
    static T max_##T(T a, T b) { \
        return a > b ? a : b;    \
    }

DEFINE_MAX(int)
DEFINE_MAX(double)

int main(void) {
    printf("%d %.1f\n", max_int(3, 9), max_double(2.5, 1.5));
    return 0;
}
Output
9 2.5
  • Verdict: idiom. C has no templates. A macro makes a copy of the function for each type, as a C++ template does, but the compiler checks only the code that the macro writes.
using System;
using System.Collections.Generic;

Console.WriteLine(Info.Describe<int>());
Console.WriteLine(Info.Describe<string>());
Console.WriteLine(new List<int>().GetType() == new List<string>().GetType());

static class Info
{
    public static string Describe<T>() =>
        $"{typeof(T).Name} {typeof(T).IsValueType} {default(T)?.ToString() ?? "null"}";
}
Output
Int32 True 0
String False null
False
  • Verdict: native. The runtime knows the type argument, so typeof(T) and default(T) work inside the generic method. List<int> and List<string> are two types when the program runs.
TypeScriptGitHub
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first<number>([3, 4]);
const s = first(["a", "b"]);
console.log(n, s);
console.log(first.length, typeof first);
Output
3 a
1 function
  • Verdict: native. The checker uses T to give n the type number | undefined and s the type string | undefined. The JavaScript that runs has one first function with one parameter and no type parameter.
package main

import (
	"cmp"
	"fmt"
)

func Max[T cmp.Ordered](a, b T) T {
	if a > b {
		return a
	}
	return b
}

type Pair[K comparable, V any] struct {
	Key K
	Val V
}

func main() {
	fmt.Println(Max(3, 9), Max("pear", "apple"))
	p := Pair[string, int]{"a", 1}
	fmt.Printf("%T %v\n", p, p)
}
Output
9 pear
main.Pair[string,int] {a 1}
  • Verdict: native. The compiler makes code for each GC shape of the type arguments and passes a dictionary that describes them. The type arguments are kept, so %T prints main.Pair[string,int].
RustGitHub
use std::mem::size_of;

trait Shape {
    fn area(&self) -> f64;
}

struct Square(f64);
struct Circle(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        3.0 * self.0 * self.0
    }
}

// A copy of this function is made for each type T.
fn area_of<T: Shape>(s: &T) -> f64 {
    s.area()
}

// One copy: the call goes through the vtable.
fn total(shapes: &[&dyn Shape]) -> f64 {
    shapes.iter().map(|s| s.area()).sum()
}

fn main() {
    println!("{} {}", area_of(&Square(2.0)), area_of(&Circle(1.0)));
    println!("{}", total(&[&Square(2.0), &Circle(1.0)]));
    println!("{} {}", size_of::<&Square>(), size_of::<&dyn Shape>());
}
Output
4 3
7
8 16
  • Verdict: native. area_of is monomorphized: the compiler makes one version for Square and one for Circle. total takes trait objects, so one copy of the code works for both. A &dyn Shape is twice the size of a &Square, because it holds a pointer to the vtable too.
  • Non-type parameters. C++ templates "are parameterized by one or more template parameters, of three kinds: type template parameters, non-type template parameters, and template template parameters"1. std::array<int, 4> has the number 4 as a template argument. Rust has const generics for the same use.
  • Templates as programs. Because the compiler runs a template for each argument, C++ code can compute at compile time. "C++ Templates are Turing complete."9
  • Specialization. "Specializations may also be provided explicitly"1: the program can give a special version of a template for one type.

Pitfalls

  • Code size. A copy for each type makes the program larger. Monomorphization "may require more compilation time and storage space due to duplicating the function body"10.
  • No primitive types in Java. Because erasure replaces a type parameter with Object, a Java type argument must be a class: "Cannot Instantiate Generic Types with Primitive Types"11. A List<Integer> holds boxed numbers.
  • No type at run time in Java. Java cannot write new T(): "Cannot Create Instances of Type Parameters"11. Pass a Class<T> or a factory function instead.
  • Templates in headers. "The definition of a class template must be visible at the point of implicit instantiation, which is why template libraries typically provide all template definitions in the headers"1. A change to a template recompiles every file that includes it.
  • Error messages. A C++ template without a concept reports an error inside its body, far from the call. Write a concept or a requires clause so that the error points to the call.

History

"Major inspirations for C++ templates were the parameterized modules provided by the language CLU and the generics provided by Ada."9 "Generic programming was introduced to the mainstream with Ada in 1977. With templates in C++, generic programming became part of the repertoire of professional library design."12 Java and C# took different ways: Java erases the type arguments4, and .NET keeps them in the runtime5.

References

  1. Templates, C++ reference, cppreference.com, Introduction
  2. Constraints and concepts, C++ reference, cppreference.com, Introduction
  3. Why Use Generics?, The Java Tutorials, Whole page
  4. Type Erasure, The Java Tutorials, Whole page
  5. Generics in the runtime, C# programming guide, Whole page
  6. Generic Data Types, The Rust Programming Language, Performance of Code Using Generics
  7. Trait objects, The Rust Reference, Introduction
  8. Generics implementation, GC Shape Stenciling, Go design document, Introduction
  9. Template (C++), Wikipedia, Introduction; Technical overview
  10. Monomorphization, Wikipedia, Introduction
  11. Restrictions on Generics, The Java Tutorials, Cannot Instantiate Generic Types with Primitive Types; Cannot Create Instances of Type Parameters
  12. Generic programming, Wikipedia, Introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • the section Cost