Template basics
As a barebones definition, we might say that a template is a block of code that doesn't exist until it is used. A template can be declared in a source module, but if it is never instantiated, it doesn't get compiled into the final binary. Further, there are different ways to declare a template and several ways to control how it is compiled into the binary. In this section, we're going to explore the former.
Templates as code blocks
A template declaration looks somewhat like a function declaration. It opens with the template
keyword, followed by an identifier, a parameter list, and then a pair of braces for the body. The body may contain any valid D declaration except module declarations, as the following example demonstrates:
template MyTemplate(T) { T val; void printVal() { import std.stdio : writeln; writeln("The type is ", typeid(T)); writeln("The value is ", val); } }
The first line declares a template
named MyTemplate
that takes one parameter, T
. This isn...