Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Classes and Templates

Template Constraints and Type Checks in D

Restrict D templates with if constraints, std.traits helpers, is expressions and static asserts so that bad type arguments fail early with clear errors.

An unconstrained template accepts every type and fails deep inside its body when the type does not fit. A template constraint rejects bad arguments at the door, makes error messages readable, and lets you provide different overloads for different kinds of types. D writes constraints with an if after the parameter list.

D code is read-only on this site. The C stand-ins use _Generic and static_assert to show the same kind of compile-time dispatch and checking.

The if constraint

D
import std.traits : isNumeric;

T average(T)(T[] values) if (isNumeric!T)
{
    T sum = 0;
    foreach (v; values) sum += v;
    return sum / values.length;
}

isNumeric!T is evaluated when average is instantiated. For int[] and double[] it is true; for string[] the template simply does not exist for that call, and the compiler says that no overload matches. Without the constraint the error would point inside sum / values.length, far from the real mistake.

Any compile-time boolean expression can go in the parentheses, and you can combine them with && and ||:

D
auto scale(T)(T x, double k) if (is(T : double) && !is(T == bool))
{
    return x * k;
}

The is expression

is(...) asks questions about types at compile time and returns a bool:

D
is(T == int)          // T is exactly int
is(T : long)          // T converts implicitly to long
is(T U == U[])        // T is a dynamic array; captures element type U
is(typeof(x.length))  // x has a .length that compiles

The last form is the heart of "duck typing" in D: check that an expression compiles instead of naming a base class. Ranges use this heavily: isInputRange!R is true when R has empty, front and popFront.

std.traits and std.range helpers

std.traits ships ready-made predicates: isNumeric, isIntegral, isFloatingPoint, isSomeString, isPointer, isCallable, isArray, and more. std.range.primitives supplies isInputRange, isForwardRange, isRandomAccessRange. Use them rather than reinventing them.

D
import std.range.primitives : isInputRange, ElementType;

auto sumAll(R)(R r) if (isInputRange!R && is(ElementType!R : long))
{
    long total;
    for (; !r.empty; r.popFront()) total += r.front;
    return total;
}

Overloading by constraint

Because constraints remove templates from consideration, you can supply several versions with disjoint constraints:

D
string kind(T)(T x) if (is(T == string))      { return "text"; }
string kind(T)(T x) if (isNumeric!T)          { return "number"; }
string kind(T)(T x) if (!isNumeric!T && !is(T == string)) { return "other"; }

Exactly one of them matches for any type. If two match, the call is ambiguous and the compiler complains, so keep the constraints mutually exclusive.

The stand-in below does this with _Generic, which picks an expression by the static type of its operand.

C Stand-in: choosing a version by type with _Generic

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.

static assert for clearer failures

When a constraint would be awkward, check inside the body:

D
struct Fixed(int bits)
{
    static assert(bits > 0 && bits <= 64, "bits must be 1..64");
    // ...
}

static assert runs at compile time and stops compilation with your message. Use it for invariants about template arguments, sizes and layouts.

C Stand-in: compile-time checks with static_assert

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.

Try changing BUFFER_SIZE to 100 and watch the compile fail with your message. That is the same experience as a D static assert.

Designing constraints well

  • Constrain on capabilities (is(typeof(a < b))) rather than concrete types when you only need a behavior.
  • Put the constraint on the template so overload resolution can use it, not just in the body.
  • For readability, name a constraint: enum isSortable(T) = is(typeof(T.init < T.init)); and then write if (isSortable!T).
  • Test both sides: add unittest blocks that confirm good types work and use static assert(!__traits(compiles, f(badValue))) to confirm bad ones are rejected.
flowchart TD
    A["Call average!T(...)"] --> B{"Constraint isNumeric!T?"}
    B -- yes --> C["Template instantiated"]
    B -- no --> D["No matching overload: clear error at call site"]

The constraint is checked before the body is compiled.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a template constraint go?

    The constraint is an if clause after the function parameters, evaluated at instantiation.
  2. 2. What does is(T : long) test?

    : means implicit convertibility; == means exact identity.
  3. 3. Which tool stops compilation with your own message when a template argument is invalid?

    static assert is evaluated at compile time and reports its message as a compile error.
  4. 4. What happens if two constrained overloads both match a call?

    Constraints should be mutually exclusive; otherwise overload resolution is ambiguous.

Summary

  • if (...) constraints reject bad template arguments early and keep errors readable.
  • is(...) and __traits(compiles, ...) test types and expressions at compile time.
  • std.traits and std.range.primitives provide the standard predicates.
  • Use static assert for invariants; make overload constraints mutually exclusive.

Next: String Mixins