Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Classes and Templates

Templates and Generics in D

Learn D templates: generic functions with type parameters, template structs and classes, value and alias parameters, specialization and implicit instantiation.

Templates are D's tool for generic programming: write a function or type once and let the compiler produce a specialized version for every type you use. Unlike generics in some languages, D templates are resolved entirely at compile time, so the generated code is as fast as hand-written code. The standard library (ranges, algorithms, containers) is built on them.

D code is read-only here. The C stand-ins use macros to generate typed functions, which is the closest plain-C relative of template instantiation.

A generic function

D
T maxOf(T)(T a, T b)
{
    return a > b ? a : b;
}

The first parentheses list the template parameters (T), the second the ordinary function parameters. You rarely write the type yourself, because the compiler deduces it:

D
int    i = maxOf(3, 8);        // T = int
double d = maxOf(2.5, 1.0);    // T = double
auto   s = maxOf!string("a", "b");  // explicit: maxOf!(string)

The ! is D's instantiation operator. With a single argument you can drop the parentheses: maxOf!int(1, 2). Each distinct T makes a separate copy of the function. If you call it with a type that has no > operator, the error appears at the instantiation point.

What the compiler really does

For every new set of template arguments the compiler stamps out code, as though you had written maxOf_int, maxOf_double and so on by hand. You can imitate this with a macro that defines a function per type.

C Stand-in: stamping out typed functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C's macros work on text and know nothing about types; D's templates are checked and can reason about types, as later lessons show.

Template structs and classes

D
struct Stack(T)
{
    private T[] items;

    void push(T value) { items ~= value; }

    T pop()
    {
        auto v = items[$ - 1];
        items = items[0 .. $ - 1];
        return v;
    }

    bool empty() const { return items.length == 0; }
}

Stack!int s;
s.push(1);
s.push(2);

Stack!int and Stack!string are two unrelated types. The same works for classes (class Node(T)), interfaces and even enums. Inside the body, T can be used anywhere a type fits.

A stand-in with a generic stack macro:

C Stand-in: a generic stack generated per type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Kinds of template parameters

Besides types, templates take values, aliases and sequences:

D
// value parameter: a compile-time constant
struct Matrix(size_t rows, size_t cols)
{
    double[cols][rows] data;
}

// alias parameter: any symbol, such as a function
auto apply(alias fn, T)(T x) { return fn(x); }

// variadic: any number of types
void show(Args...)(Args args)
{
    foreach (a; args) writeln(a);
}

Matrix!(2, 3) and Matrix!(3, 3) are different types, so adding a 2x3 to a 3x3 can be rejected at compile time. alias parameters let you pass a function or lambda without a function pointer, and the call is usually inlined. Args... is a type sequence, which is how writeln accepts anything.

You can give parameters defaults: struct Buffer(T = ubyte, size_t N = 256).

Specialization

A template can have a general form and special forms for specific types:

D
void describe(T)(T x)  { writeln("something: ", x); }
void describe(T : int)(T x) { writeln("an integer-like: ", x); }

T : int means "any T implicitly convertible to int". Another style is to branch inside the body with static if (see static if and traits), which most D programmers prefer because it keeps one body.

Eponymous templates and shorthand

When a template contains one member with the same name as the template, using the template name gives that member directly. That is why maxOf!int(1, 2) calls the function and not the "template". The same rule powers compile-time helpers such as enum isSmall(T) = T.sizeof <= 8;.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does T maxOf(T)(T a, T b) declare?

    The first parenthesized list holds the template parameters, the second the function parameters.
  2. 2. What does Stack!int mean?

    ! instantiates a template with the given arguments.
  3. 3. When are D templates resolved?

    Templates are instantiated by the compiler, producing separate specialized code.
  4. 4. Which parameter kind lets you pass a function without a function pointer?

    An alias template parameter accepts any symbol, including functions, and calls through it can be inlined.

Summary

  • Templates generate specialized code at compile time; types are deduced when possible.
  • Name!(args) instantiates; T, values, alias and Args... can all be parameters.
  • Structs, classes, interfaces and functions can all be templates.
  • Specialization and static if handle special cases; see the next lesson for constraints.

Next: Template Constraints