The definition of templates in D

FeepingCreature default_357-line at yahoo.de
Sat Mar 17 23:01:00 PDT 2012


A template is a parameterized namespace. That is, it is a namespace (a name through which other objects can be accessed) that may be passed parameters that can modify the nature of the stuff inside.

If a template is a compile-time function, then the equivalent of a function call - the association of a template description with
specific arguments - is called a template instantiation.

Templates have the following properties:

* they're unique; that is, a member of a template instantiation always refers the same as a member of the same instantiation in a different module

* they're compiletime; that is, it is impossible to instantiate a template while the program runs.

* In D, if a template contains only one member, and its name is the same as the template, then the member is assumed to *be* the template instantiation.

That's all!

In D, void foo(T)(T t) { } is just short for template foo(T) { void foo(T t) { } }.

So foo!(int) == "member foo of instantiation of template foo with parameter T = int".

There's a shortcut for this, called IFTI, "implicit function template instantiation". If you have a function template - that is,
a template containing only one function with the same name as the template - then calling the template as if it was a function will
simply instantiate it with the type of the arguments.

Example:

template bar(T...){ void bar(T t) { writefln(t); } }

bar(2, 3, 4); // is equivalent to
bar!(int, int, int)(2, 3, 4); // is equivalent to
bar!(int, int, int).bar(2, 3, 4);



More information about the Digitalmars-d mailing list