Templates everywhere

bearophile bearophileHUGS at lycos.com
Sun Mar 14 14:10:04 PDT 2010


Walter Bright:

>Years ago, although I had implemented templates for C++, I didn't "get" them. Not at all.<


>It isn't the concept or application of templates that is hard. It's the C++ syntax for them that's hard. It's hard in C++ because when they were designed, little was known or understood about what templates were good for and how they should be used. Now that we do know, we can make a much more straightforward design.<

I agree that D syntax makes templates simpler (and the semantics too has being cleaned up), and I like them in D.

What's the purpose of templates in D? I think they have few main purposes:
1) Allow for type-safe compile-time genericity for collections and algorithms.
2) Perform some kind of usually simple "processing" on types, for example to determine what's the output type given two different input types. So types can be seen as compile-time variabiles for templates. Such processing is often related to the first purpose.
3) They can be used to perform compile-time computations on variables, for example to fill a data structure at compile-time. This is useful, but much less useful than the first two purposes of templates. Today in D this can often be done by CTFE that is getting better and better (thanks to Don too), so often today in D it's bad to use templates for this purposes. CTFE functions can be templated, so they can sometimes do what pure templates can do over types, with a much better syntax.
 
In Java and C# there are generics systems that are quite less powerful than C++ templates, their purpose is mostly the first one in my list. Being less powerful they can (in theory) keep the language simpler to learn and use (in practice Java generics have several corner cases. And in C#4 there is a way to specify a collection to be covariant, contravariant, etc).

So can explicit templates be "removed" from a C++/D-like language, and replaced by simpler generics, plus CTFE, plus a variable type (that is used at compile-time only by CTFE functions) that can contain a type? (Note that the end result is more or less the starting point. It's mostly a syntax shuffle).

If I am not saying silly things, then the end result is a language with a semantics similar of D (it can do the same things), but with a little simpler syntax, because for the eyes of the programmer it contains functions only (plus classes, structs, etc).

Bye,
bearophile



More information about the Digitalmars-d mailing list