How Different Are Templates from Generics

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Oct 12 21:44:57 UTC 2019


On Saturday, October 12, 2019 2:11:28 PM MDT jmh530 via Digitalmars-d-learn 
wrote:
> On Friday, 11 October 2019 at 17:50:42 UTC, Jonathan M Davis
>
> wrote:
> > [snip]
>
> A very thorough explanation!
>
> One follow-up question: would it be possible to mimic the
> behavior of Java generics in D?

Yes, but it's unlikely that it would make any sense to do so. You'd
basically have to do something like

auto foo(T)(T obj)
    if(is(T : Object) && !is(T == Object))
{
    return foo(cast(Object)obj);
}

auto foo(Object obj)
{
    ...
}

And for containers, you'd basically end up with a templated container that
was just a wrapper around a non-templated container that operated on Object.

If you went with such an approach, you'd get less code in the binary, but
you'd also end up with a deeper call stack because of all of the wrappers
needed to add the casts for you.

However, since Object can't do much of anything, having code that operates
on Object isn't usually very useful. You could have the code use a different
base class that had whatever operations you wanted, but you're still adding
a fair bit of extra machinery just to avoid a few template instantiations.

And since idiomatic D doesn't use classes much (rather, best practice is to
use a struct unless you need polymorphism or you need something to always be
a reference type), and it uses templates quite heavily (that's especially
true with range-based code), it would be pretty bizarre to try and use
Java's approach in D.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list