Why Templates?

John C johnch_atms at hotmail.com
Mon Mar 6 01:48:24 PST 2006


"Don Clugston" <dac at nospam.com.au> wrote in message 
news:dugufa$2udq$1 at digitaldaemon.com...
> Walter Bright wrote:
>> "John C" <johnch_atms at hotmail.com> wrote in message 
>> news:dufl8l$14au$1 at digitaldaemon.com...
>>> "Walter Bright" <newshound at digitalmars.com> wrote in message 
>>> news:dufcpn$p1n$2 at digitaldaemon.com...
>>>> Technically, Java and C# implement generics, not templates. C++ and D 
>>>> implement templates, not generics.
>>>>
>>>> What's the difference? One way to think about it is generics are 
>>>> handled at run time (by casting), templates at compile time.
>>> I'm sure you're wrong about C#'s implementation using casts. Java 
>>> generics do erase the type information and cast everything to an object. 
>>> But the CLR was reworked to support generics so List<int> remains a list 
>>> of ints until it's instantiated at runtime.
>>
>> From what I read, C# generics do not instantiate a new routine for every 
>> set of argument types, it implements *one* routine which handles them all 
>> via casting.

I just wanted to put the record straight. For reference types, the same code 
is shared, but full type information is maintained, and there's no 
Object-to-type cast. With value types and structs, separate sections of code 
are created to explicitly avoid boxing/unboxing.
>
> It looks as though it has an optimisation for built-in types.
> http://www.artima.com/intv/generics2.html

There's a more technical overview here:
http://research.microsoft.com/projects/clrgen/generics.pdf

>
> Clearly C# does it a lot better than Java does. Java generics seem to be 
> 100% syntactic sugar.
>
> There's a valid point raised there about the cryptic error messages 
> generated in C++ templates. Currently D error messages for templates are 
> even worse, but this is mainly because it keeps tying to instantiate 
> templates after one has failed (and you can't even press ctrl-c to stop 
> the torrent, which can last for over a minute). This is another area where 
> D could give a great improvement over C++.
>

Yes, template error messages are notoriously difficult to decipher. 
Compilers need to address this. 





More information about the Digitalmars-d mailing list