Kinds of Templates

Get introduced to the kinds of templates.

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 ~=!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 in the following subclass may give the impression that it is overriding a function, it actually hides the put name of the superclass.

Get hands-on with 1000+ tech skills courses.