Thursday, September 20, 2007

Template metaprogramming

Following up on the subject regarding my last post Generics, another type of metaprogramming I found a interesting Wikipedia article Template metaprogramming. Quoting (as I usually do);

Template metaprogramming is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time execution. The technique is used by a number of languages, the most well-known being C++, but also D, Eiffel, Haskell, ML and XL.”

The article makes it very clear that Templates is a compile time metaprogramming technique. This is something that I have pointed out in my earlier posts about metaprogramming aswell. Also the article compares Templates with Macros but points out that Macros is type unaware whilst Templates is aware of the types in the native language. All this with the exception of Lisp since Lisp Macro language is Lisp itself.

“Some common reasons to use templates is to implement generic programming (avoiding sections of code which are similar except for some minor variations) or to perform automatic compile-time optimization such as doing something once at compile time rather than every time the program is run, for instance having the compiler unroll loops which would otherwise not be.”

Reading this I am thinking, so I can use templates on other stuff than as a placeholder for a unknown type. And truly spoken, only a couple of lines further reading gives me a sweet example of how to use the compiler to pre calculate the factorial value of any given constant. This gives me a whole new view of Templates and what can be accomplished with them. The article goes on and describes another couple of interesting usage patterns for Templates.

Well worth reading!

No comments: