Search code examples
templatesgenericsd

Dlang generics for classes


first time poster. I've been using Java for a few years now, and have decided to learn D. In Java, you can declare a class with a generic type, and create a new object from that class. Like:

public class foo<T>
{
    public foo() { ... }
}

and then simply call foo<String> f = new foo<>();. I tried to implement the same in D, but I got a compile error like: "class core.collection.RingBuffer.RingBuffer(T) is used as a type". Looking at the tutorials for D, I have found that generic programming is implemented using templates. However, I cannot make heads or tails of the official tutorials/docs. Could someone please explain it to me? Thanks.


Solution

  • That error comes when you don't instantiate the template on the right hand side - it complains "foo is used as a type" because foo itself isn't a type yet, it is a template for a type. That means it doesn't become an actual type until instantiated with !(arguments).

    Your Java code of new foo<>() isn't exactly how it would be in D: in D, you need to give the type over there on the right hand side.

    So try:

    foo!string f = new foo!string();
    

    or

    foo!(string) f = new foo!(string)();
    

    The parenthesis around the template arguments, following the !, are optional if there is just a single word after it, so both of those mean the same thing.

    Writing the type twice isn't required in D, but instead of leaving it out of the right side, you can leave it off the left side with type inference. This will compile too:

    auto f = new foo!string();
    

    and that's pretty common in D.