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:
template `!=` (a, b: untyped): untyped =
# this definition exists in the System module
not (a == b)
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.
当前内容版权归 nim-lang.org 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 nim-lang.org .