How does D's templated functions implementation differ from generics in C#/Java?
Adam D. Ruppe
destructionator at gmail.com
Fri Aug 7 21:43:44 UTC 2020
On Friday, 7 August 2020 at 21:03:47 UTC, aberba wrote:
> Syntactically they look the same (although D's can do more
> things) so I'm trying to understand how why in D it's called
> template but in languages like C#/Java they're generics.
In D, a copy of the function is created for each new template
argument type. In Java (and I assume C# but I don't know for
sure), there's just one copy of the function and the types are
erased to call it.
So let's take a D template `sort(T)(T list)`. The compiler
generates nothing until you pass it arguments; it is just a
template in its memory. Pass it int and it generates a whole
new function sort(int list). Pass it float and it generates
another, totally separate function sort(float list).
Now, take a Java generic function `sort(List<T> list)`. The
compiler will generate a function `sort(List list)`. Pass it a
List<Integer> and the compiler actually will just cast it back to
the List interface and pass it into the one function it already
generated; this creates no new code. At runtime, you cannot tell
it was a List<Integer>, only the compiler knew that*.
Pass it a List<Float> and again, the compiler will just cast it
back to the interface and give it to the same `sort(List list)`
function. The actual generic type is known only to the Java
compiler and at runtime it is basically a bunch of hidden casts
to make it work.
* the java runtime is free to optimize a bit more based on usage
with its jit compiler but that doesn't change much in the concept.
you can read some more here
A cool thing with Java's thing though is since they are just
special kinds of interface methods you can access generics
through runtime reflection in it, whereas D's templates cease to
exist at runtime. Only the generated instances of them are around
by then since the template itself only lives in the compiler's
memory for it to make copies of to generate instances.
More information about the Digitalmars-d-learn