Function Templates

Let’s learn about function templates and see how to use more than one template parameter.

We'll cover the following

Defining a function as a template means leaving one or more of the types it uses as unspecified, to be deduced later by the compiler.

The types that are left unspecified are defined within the template parameter list, which comes between the name of the function and the function parameter list. For that reason, function templates have two parameter lists:

  • template parameter list
  • function parameter list
void printInParens(T)(T value) {
    writefln("(%s)", value); 
}

The T within the template parameter list above means that T can be any type. Although T is an arbitrary name, it is an acronym for “type” and is very common in templates.

Since T represents any type, the templated definition of printInParens() above is sufficient to use with almost every type, including user-defined ones:

Get hands-on with 1400+ tech skills courses.