Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

Template Constraints

Templates are normally overloaded and matched based on the template arguments being matched to the template parameters. The template parameters can specify specializations, so that the template argument must match particular type patterns. Similarly, template value arguments can be constrained to match particular types.

template Foo(T) { ... }
template Foo(T : T*) { ... }
template Foo(T : T[]) { ... }

alias f1 = Foo!(int);   // picks Foo(T)
alias f2 = Foo!(int*);  // picks Foo(T : T*)
alias f3 = Foo!(int[]); // picks Foo(T : T[])

But this has its limitations. Many times there are arbitrarily more complex criteria for what should be accepted by the template. Such criteria could be to:

Constraints address this by simply providing a boolean expression that is evaluated at compile-time, after the arguments are matched to the parameters. If that boolean is true, then the template is a valid match for the arguments, if not, then the template does not match and is passed over during overload matching.

The constraint expression follows the template declaration and the if keyword:

template Foo(int N)
    if (N & 1)
{
    ...
}

which constrains the template Foo to match only if its argument is an odd integer.

Predicate Functions

Arbitrarily complex criteria can be used, as long as it can be computed at compile time. For example, here's a template that only accepts prime numbers:

bool isPrime(int n)
{
    if (n == 2)
        return true;
    // 0, negative and even numbers are not prime
    if (n < 1 || (n & 1) == 0)
        return false;
    if (n > 3)
    {
        // check possible odd integer denominators
        for (auto i = 3; i * i <= n; i += 2)
        {
            if ((n % i) == 0)
                return false;
        }
    }
    return true;
}

template Foo(int N)
    if (isPrime(N))
{
    // ...
}

alias f1 = Foo!(5);    // ok, 5 is prime
//alias f2 = Foo!(6);    // error: no match for Foo
//alias f3 = Foo!(9);    // error: no match for Foo
Note: isPrime is called using Compile-Time Function Evaluation.

is Expressions

Type constraints can be complex, too. With type specialization alone, a template Bar that will accept any type that implicitly converts to a built-in floating point type must use template overloads:

template Bar(T:float)
{
    ...
}
template Bar(T:double)
{
    ...
}
template Bar(T:real)
{
    ...
}

and the template implementation body must be duplicated three times. But with constraints, this can be specified with one template:

template Bar(T)
    if (is(T : float) || is(T : double) || is(T : real))
{
    ...
}

Unlike with parameter specialization, types with implicit conversion to floating point can be ruled out with a different constraint:

template Bar(T)
    if (is(T == float) || is(T == double) || is(T == real))
{
    // ...
}

alias b1 = Bar!float; // OK
//alias b2 = Bar!int;   // error

See IsExpression for more tests.

The above example can be simplified by using the isFloatingPoint template in library module std.traits:

import std.traits;

template Bar(T)
    if (isFloatingPoint!(T))
{
    ...
}

__traits

Characteristics of types can be tested, such as if a type instance can be added:

// Returns true if instances of type T can be added
// Works by attempting to add two instances of type T
const isAddable(T) = __traits(compiles, (T t) { return t + t; });

auto twice(T)(T t)
    if (isAddable!(T))
{
    return t + t;
}

// an addable struct type
struct S
{
    int i;

    S opBinary(string op : "+")(S s)
    {
        return S(i + s.i);
    }
}

void main()
{
    assert(twice(4) == 8);
    S s = {2};
    assert(twice(s).i == 4);
    //twice("a"); // fails to match
}

__traits(compiles) is used to check if a function literal successfully compiles. Other expressions can be used instead of a function literal. The expression is not evaluated. Other compile-time __traits are available.

Note: The function literal above declares an argument of type T to obtain an instance of T without having to construct it.

Since any expression that can be computed at compile time is allowed as a constraint, constraints can be composed:

T foo(T)(T t)
    if (isAddable!(T) && isMultipliable!(T))
{
    return t + t * t;
}

Constraints can deal with multiple parameters:

template Foo(T, int N)
    if (isAddable!(T) && isPrime(N))
{
    ...
}

A more complex constraint can specify a list of operations that must be doable with the type, such as evaluating template isStack which requires that the type has a type property ValueType, and that 4 functions exist which take an instance of the type, 2 of which return certain values:

const isStack(T) =
    __traits(compiles,
        (T t)
        {
            T.ValueType v = top(t);
            push(t, v);
            pop(t);
            if (empty(t)) { }
        });

template Foo(T)
    if (isStack!(T))
{
    ...
}

Overloading based on Constraints

Given a list of overloaded templates with the same name, constraints act as a yes/no filter to determine the list of candidates for a match. Overloading based on constraints can thus be achieved by setting up constraint expressions that are mutually exclusive. For example, overloading template Foo so that one takes odd integers and the other even:

template Foo(int N) if (N & 1)    { ... } // A
template Foo(int N) if (!(N & 1)) { ... } // B
...
Foo!(3)    // instantiates A
Foo!(64)   // instantiates B

Note the above 2 templates could be combined using static if:

template Foo(int N)
{
    static if (N & 1)
        // body of A
    else
        // body of B
}

Constraints are not involved with determining which template is more specialized than another.

void foo(T, int N)()        if (N & 1) { ... } // A
void foo(T : int, int N)()  if (N > 3) { ... } // B
...
foo!(int, 7)();   // picks B, more specialized
foo!(int, 1)();   // picks A, as it fails B's constraint
foo!("a", 7)();   // picks A
foo!("a", 4)();   // error, no match

References