Nobody understands templates?

Frustrated Frustrated at nowhere.com
Fri Feb 28 15:37:19 PST 2014


On Friday, 28 February 2014 at 18:42:57 UTC, 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?
>

Yes.

Templates are awesome. I use them when ever I can. They allow you 
to simplify the tasks.

If you check out my thread about dependencies you can see a good 
example.

iGui             -->        iButton
  |
  |
  |> WindowsGui   -->        WindowsButton
  |
  |> LinuxGui     -->        LinuxButton


When programming to interfaces you lose the ability to use 
concrete types easily. E.g., WindowsGui can't use a WindowsButton 
because it has to implement iGui, which uses iButton... even 
though WindowsButton is an iButton and the only one we want to 
use with WindowsGui.

But as far as WindowsGui is concerned, there is no iButton but 
just a WindowsButton(Because it doesn't care about being 
general... and doesn't care about LinuxButton, RogueButton, or 
whatever).

In some sense, iButton was meant to be used with iGui and 
WindowsButton for WindowsGui... but we can't do this easily in 
D... well, unless you use a template to generate all the crap 
code you would normally have to write.

So a template(compile time construction) can help do things 
easier than you could otherwise... and if you do them right they 
are generic enough to be used in general things. (like anyone 
could use the template I created to help them with the same type 
of problem)

You are missing the point because the whole reason templates are 
generally used in libraries is because they are so powerful(you 
want to reuse them).


In the example I give above, the mixin template reduces code 
bloat and error proneness significantly for large classes and 
makes you feel like you are writing classes like you would 
normally write them when not using interface programming.

Basically until you start using templates a lot you won't know 
where to use them in the first place. You just gotta get used to 
them and then you'll start trying to use them everywhere.

(granted, I'm using mixin templates but templates nonetheless)


More information about the Digitalmars-d-learn mailing list