Why does D not have generics?

Adam D. Ruppe destructionator at gmail.com
Tue Jan 12 14:45:36 UTC 2021


On Tuesday, 12 January 2021 at 13:36:09 UTC, Ola Fosheim Grøstad 
wrote:
> I think you guys have something more specific in mind based on 
> C#/Java?

Yeah, in the D context since we obviously have generic templates, 
I'd take it to mean the Java style.

A Java generic doesn't generate new code for other types at all. 
It is just a runtime class that works in terms of interfaces, and 
when the compiler parameterizes it, it basically just inserts 
static casts at the interface boundary for you.

The benefit of this is you have almost zero compile time cost and 
runtime cost comparable to any other class. It avoids template 
bloat in codegen that can be very significant in D.

I'd love to have it as an option in D as well. There's a lot of 
types that can use identical runtime code and just change types. 
Not just classes, but like integer types too can be identical and 
merged, const/immutable/shared/etc can be identical and merged, 
and even other things with cast(void*) can do it.

Lots of potential for use inside druntime itself, changing the 
existing void* + TypeInfo pairs into templates can mean no more 
annoying typeinfo requirement... but then it causes runtime 
bloat. So we probably actually do want to merge, and Java-style 
generics are a very good way to do it.

We could like, just for example

_d_arrayappend(ref T[] arr, E ele)

forward back to the same implementation functions with pointers, 
static if branching on special requirements like postblit, just 
passing the exact parameters it needs to make it work instead of 
typeinfo... but then having no additional codegen, no additional 
symbols, no additional indirection, by using the generics.

Doing this in today's D comes close with inlined templates but it 
is still far more expensive than it has to be and really annoying 
to try to describe. A sum type definition in the template that 
actually merges would surely help.


More information about the Digitalmars-d mailing list