Java-like generics in D
Reiner Pope
some at address.com
Mon Aug 13 00:40:21 PDT 2007
Frank Benoit wrote:
> As addition to the existing templates, i think java like generics would
> be very helpful for D.
>
> The generic could be like this:
> 1) use the new keyword 'generic' instead of 'template'
> 2) Typeparameter can only be object or interface types
> 3) the compiled code does not know the exact type of the instantiation
> parameter. (type erasure)
> 4) the compiler 'inserts' missing casts for the given instantiation type
> parameters
>
> Advantages:
> 5) "lightweight templates", because of no more object code duplication
> for new instantiations.
> 6) the compiler can generate the object code independantly of the
> intantiation code
> 7) no more errors like 'forward reference' for generic, because the
> generic can compile without the knowledge of the exact types.
>
> Does that make sense?
>
It certainly makes sense. There's also the point (or is this what you
mean by #6?) that don't need to distribute your source code for your
generic type.
But this is a job for current D: in fact, I had been hoping for
compile-time reflection in order to allow this, and I have started
writing an implementation.
The basic idea is that there's a wrapper template, with prototype as
follows:
template GenericOf(alias Impl, Args...)
The aim is for the GenericOf template to make one (actually, currently
it makes two -- one for the actual implementation, and one with
distinctive types so that the template parameters can be recognised)
instantiation of Impl, and expose a template which wraps this
instantiation, providing conversions to and from the base types, so that
no conversions have to be done at the call site.
I don't know exactly how the C++ version of this -- using a void*
instantiation -- works, but I plan to make something more expressive.
The Args... tuple specifies for each argument what requirements are
placed on the types (this currently just means the base type, and
wrapping for structurally-conforming types if desired), mimicking
template parameter specialisations, and allowing functions specific on
that type to be called (not possible if you just use a void* instantiation).
In addition, it is neat because you still write your collection as a
template, and just expose the generic with a line like
alias GenericOf!(MyCollection, ParameterRequirements)
MyGenericCollection;
-- Reiner
More information about the Digitalmars-d
mailing list