Understanding Templates: why can't anybody do it?

Entity325 lonewolf325 at gmail.com
Sat Mar 17 10:14:47 PDT 2012


(Sorry if this is the wrong place for this, or if there's already 
a thread in existence which would be better.  If either of these 
is the case, simply point me in the right direction, and I'll be 
on my way.)

My first interaction with Templates was about 5 years ago, in a 
C++ class at my university.  I immediately thought "A general 
type?  This would be great for my logger!" and tried to implement 
them into the small library I had been developing to save time on 
the class assignments.

Naturally, I didn't understand them, so after a couple of 
half-hearted attempts, I gave up and went back to doing things 
the way I had before.  I've avoided Templates since then, because 
they don't make any sense!

5 years later, enter D.  In the process of trying to teach myself 
some D, I've found myself with a library of Structs for which the 
operator overloading features are extremely handy.

Teensy problem here: the documentation on how to use operators 
makes use of Template types in the examples.

Having developed a bit more analytical skill and tenacity in the 
intervening years, I resolved to actually figure the mess out 
this time.  I have come to a conclusion.

The reason nobody understands Templates is that nobody 
understands them.

That is to say, nobody understands how Templates work is because, 
as was the case for me, the sum total of explanation we are given 
on them in programming class is "These are Templates.  They 
exist.  They look something like this."

Even the (quite thorough) documentation for the D language 
reference isn't immune to this, if we take a look.  
(http://dlang.org/template.html) As you can see, the page more or 
less starts off with "--And here are some cool things you can do 
with templates."

Wait, what?  I feel like I've started watching Primer 20 minutes 
before the end, without anybody telling me what's going on.

Herein, I think, lies the root of the reason why nobody 
understands Templates.  I think the solution to this problem is 
not to comfort programming students by saying "Don't worry, 
nobody understands Templates."  I think it's time we collectively 
figured out what they are.  That done, we can overhaul the way 
new programmers learn how to use them.

Who's with me?  Anybody have a short(but COMPLETE!) example of 
code that makes use of Templates that you actually understand 
what's going on there?


More information about the Digitalmars-d mailing list