A Beginner's Guide to D/Templates and Generic Programming/Template Functions

Just as template classes allow the writing of generic data structures, template functions allow the writing of generic algorithms. Generally speaking, template functions allow the library writer to write functions for argument types without having to overload the function with the same code.



A template function looks like a regular function with two sets of arguments:

foo(T, U) (T t, U u)

The first set of arguments are the template arguments. (See the section on template classes for what are allowed as template arguments.) The second set of arguments are the regular function arguments.

In the case of the above example, the function can just be called by passing the regular function arguments. D will derive the template parameters automatically based on the types of the arguments. This is called implicit function template instantiation, or IFTI for short.

Function templates may be explicitly instantiated like any other template, as in foo!(int, char[])(12, "hello").



The classic example of a template function is the min function:

T min(T) (T t1, T t2)
    if (t1 < t2) return t1;
    else return t2;

This function determines which of any two arguments (of the same type) are smaller. (With the stupid caveat that it will return the second argument if they are equal.)

min(12, 20); // Returns 12
min("green"[], "blue"); // Return "blue"

(A note about the second example. We pass min a slice of "green", because otherwise D will infer the type of the argument to be char[5], a static array. The type of "blue" is char[4], a different type. By slicing "green", we get a char[], a dynamic array, and D knows how to implicitly convert "blue" to this type.)