Nobody understands templates?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 28 12:37:54 PST 2014


On Fri, Feb 28, 2014 at 06:42:57PM +0000, Steve Teale wrote:
> All the D aficionados seem to wet their pants over
> meta-programming, but I struggle to find a place to use it.
> 
> IIRC, I used it in a couple of places when I was trying to write
> library stuff for MySQL, but in my current project, I use it only
> once. That's when I want to stuff something onto my undo stack.
> 
> For that I have two template functions - push(T)(MybaseClass* p,
> T t, int ID), and pushC, which is just the same except that it
> checks the top of the stack to see if the ID there is the same as
> what it is wanting to push.
> 
> This has served me very reliably, but I struggle to find other
> places in the whole application where I would benefit from
> templates.
> 
> Is this typical - libraries use templates, applications don't, or
> am I just being unimaginative?
[...]

As others have said, it depends on your needs and what you're trying to
accomplish. :) If you find that your code contains some functions that
are generically applicable, you can turn them into templates. Or leave
them as normal functions until another piece of code needs to call it
with different parameter types, then turn it into a template. A lot of
my code starts out that way and turn into templates once it becomes
clear that they are generically applicable.

It's also some degree of future-proofing: I work with numerical
software, for example, and knowing that one day I might desire to
substitute the built-in floating point types with, say, something that
can represent quadratic rationals (numbers of the form a+b*√c) exactly,
is an indication to me that functions that operate on these quantities
should be templated on the number type.

But on the other hand, if something doesn't *need* to be a template,
then don't use templates. :) It depends on what you're trying to
accomplish. Use the right tools for the job. Not every problem is a nail
to be hammered; sometimes using a screwdriver for a screw is just what
you need.


T

-- 
There are two ways to write error-free programs; only the third one works.


More information about the Digitalmars-d-learn mailing list