How does D's templated functions implementation differ from generics in C#/Java?

H. S. Teoh hsteoh at
Sat Aug 8 06:35:29 UTC 2020

On Sat, Aug 08, 2020 at 01:47:27AM +0000, jmh530 via Digitalmars-d-learn wrote:
> On Friday, 7 August 2020 at 21:39:44 UTC, H. S. Teoh wrote:
> > [snip]
> "Furthermore, it can dispatch to a type-erased implementation ala Java
> -- at your choice;"
> This is interesting. Would you just cast to Object?

You could. Or you could introspect a type and dispatch a subset of types
to a type-erased implementation, say under some base class of your
choice or something. Or even something else altogether, like a C-style
void*-based implementation.

Or a hybrid, like this:

	class ContainerBase {
		class Node {
			Node next, prev;
			... // generic methods independent of element type

	class Container(T) : ContainerBase {
		class Node : ContainerBase.Node {
			T payload;
			... // T-specific methods

The code in ContainerBase deals with the element-independent part of the
container, essentially the type-erased component, whereas Container!T
retains type information for working with type-specific operations.
Result: reduced template bloat like Java generics, yet without giving up
the advantages of retaining element type information.

You couldn't do such a thing in Java, because Java-style generics simply
aren't powerful enough.


Truth, Sir, is a cow which will give [skeptics] no more milk, and so they are gone to milk the bull. -- Sam. Johnson

More information about the Digitalmars-d-learn mailing list