Templates

A template is a simple form of a macro: It is a simple substitution mechanism that operates on Nim’s abstract syntax trees. It is processed in the semantic pass of the compiler.

The syntax to invoke a template is the same as calling a procedure.

Example:

  1. template `!=` (a, b: untyped): untyped =
  2. # this definition exists in the System module
  3. not (a == b)
  4. assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))

The !=, >, >=, in, notin, isnot operators are in fact templates:

a > b is transformed into b < a.
a in b is transformed into contains(b, a).
notin and isnot have the obvious meanings.

The “types” of templates can be the symbols untyped, typed or typedesc. These are “meta types”, they can only be used in certain contexts. Regular types can be used too; this implies that typed expressions are expected.