Template meta programming

If you ever got in touch with template meta programming in C++ you will be relieved what tools D offers to make your life easier. Template meta programming is a technique that enables decision-making depending on template type properties and thus allows to make generic types even more flexible based on the type they are going to be instantiated with.

static if & is

Like the normal if, static if conditionally compiles a code block based on a condition that can be evaluated at compile time:

static if(is(T == int))
    writeln("T is an int");
static if (is(typeof(x) :  int))
    writeln("Variable x implicitely converts to int");

The is expression is a generic helper that evaluates conditions at compile time.

static if(is(T == int)) { // T is template parameter
    int x = 10;

Braces are omitted if the condition is true - no new scope is created. { { and } } explicitly create a new block.

static if can be used anywhere in the code - in functions, at global scope or within type definitions.

mixin template

Anywhere you see boiler plate, mixin template is your friend:

mixin template Foo(T) {
    T foo;
mixin Foo!int; // int foo available from here on.

mixin template might contain any number of complex expressions that are inserted at the instantiation point. Say good-bye to the pre-processor if you're coming from C!

Template constraints

A template might be defined with any number of constraints that enforce what properties a type must have:

void foo(T)(T value)
  if (is(T : int)) { // foo!T only valid if T
                     // converts to int

Constraints can be combined in boolean expression and might even contain function calls that can be evaluated at compile-time. For example std.range.primitives.isRandomAccessRange checks whether a type is a range that supports the [] operator.


Basics references

Advanced references

rdmd playground.d