tags:

views:

428

answers:

6

We all know the usual use of templates to design containers and we all know that you can do things with templates that will make your head spin.

When I first encoutered static polymorphism I was really struck on what you can do with templates. It's obvious that templates are useful for more than for designing containers. I bought Andrei's "Modern C+ Design" but sadly haven't yet found the time or concentration to read it but I'm sure it offers a wealth of brilliant uses of templates.

IMHO this is also a very clever use of templates.

What's the most ingenious use of templates you've ever encountered?

+8  A: 

Boost's foreach explained by its author.

tpdi
+5  A: 

boost's Spirit meta programming for creating a parser's grammar.

shoosh
I'm also very fascinated by boost::Spirit
Wolfgang Plaschg
+4  A: 

Compile time assert using template specialization. I think it is so simple yet so beautiful use of templates.

Naveen
+2  A: 

Alexandrescu's work on templates is fascinating. The Loki library amply demonstrates the magic he can weave with templates.

dirkgently
+1  A: 

I rather like Microsoft's "smart pointers" that make elaborate use of templates to make COM less of a pig and code much more readable.

Peter Wone
+1  A: 

I don't remember the lib name, but the idea was to use templated types parameterized by integers in order to enforce consistency when doing consistency when performing computation among physical quantities. The concept is very simple, take a templated type that simply embeds a double precision float. Parameterized with three integers, one for mass, one for distance, one for time. For example a velocity is distance parameter = 1 and time parameter = -1. An acceleration is distance parameter = 1, time parameter = -2. And then overload all operators, so that you can only add/subtract types with the same parameters, and the you sum the parameters when doing a product. So if velocity is Type<1,-1,0> and time is Type<0,1,0>, then velocity x time is Type<1+0,1+-1,0+0>, so velocity*time -> distance.

Not only it is smart but it is one of the very few examples of a good use of templates with parameters other than typename