Kinds of Templates
Discover various kinds of templates in D, including member function templates, union templates, and interface templates. Learn how these templates enable flexible code design, support type customization, and enhance efficiency. Understand template instantiation nuances and how to leverage them for advanced programming tasks.
We'll cover the following...
We have already covered function, class, and struct templates in the templates chapter and we have discussed many examples of them since. Let’s look at some more kinds of templates.
Member function templates
struct and class member functions can also be templates. For example, the following put() member function template works with any parameter type as long as that type is compatible with the operations inside the template (For this specific template, it should be convertible to string.):
class Sink {
string content;
void put(T)(auto ref const T value) {
import std.conv;
content ~= value.to!string;
}
}
However, as templates can have a potentially infinite number of instantiations, they cannot be virtual functions because the compiler cannot know which specific instantiations of a template to include in the interface. (Accordingly, the abstract keyword cannot be used either.)
For example, although the presence of the put() template ...