C++ Template Metaprogramming
I have not used C++ in many years. It was so long ago that templates, in the way they are used today, were not in C++ yet. I hope I never have to program in C++ again. That said, it’s interesting to know that C++ templates are so powerful that you can write a compile-time Lisp interpreter in them!
The following is from the notes at Amazon about the book “C++ Template Metaprogramming” by David Abrahams and Alexey Gurtovoy:
“In 1998 Dave had the privilege of attending a workshop in Generic Programming at Dagstuhl Castle in Germany. Near the end of the workshop, a very enthusiastic Kristof Czarnecki and Ullrich Eisenecker (of Generative Programming fame) passed out a few pages of C++ source code that they billed as a complete Lisp implementation built out of C++ templates. At the time it appeared to Dave to be nothing more than a curiosity, a charming but impractical hijacking of the template system to prove that you can write programs that execute at compile time. He never suspected that one day he would see a role for metaprogramming in most of his day-to-day programming jobs.”
Thanks for David Mankins for bringing this to my attention!
I recently learned about Python’s powerful metaprogramming techniques, from a talk by Adam Baratz of The Echonest. This was very impressive and I hope to find time to learn more.
September 10th, 2009 at 11:17 am
Do you know where to find this Lisp-in-C++ code? It looks like fun.
September 10th, 2009 at 11:23 am
C++ templates are an interesting curiosity to me. I work with a certified (and certifiable?) C++ fanatic who things they’re the bees knees. I’ve even used them myself on non-trivial production code. (As a simple “type safe preprocessor”, as I like to think of them, they’re not too bad.) But every time I look at the examples that the C++ nuts think are totally awesome, I’m horrified. The syntax is so arcane (and ugly!) that I can’t help but think to myself: “How much do I have to hate myself to think this is a good idea.”
September 10th, 2009 at 2:01 pm
As far as I understand, the C++ template system is Turing-complete. Now, that doesn’t mean it’s easy to use for anything more than simple type polymorphism…
September 11th, 2009 at 6:11 am
@Bob Miller: Sorry, I don’t know anything beyond that quotation.
September 11th, 2009 at 8:33 am
Greenspun’s 10th Law FTW!
September 12th, 2009 at 1:23 pm
I love the fact that
vector<vector<int>>
is a syntax error. Nothing says more about the way C++ evolved than that trivial little gotcha!
September 12th, 2009 at 1:34 pm
Well, it is a -different- syntax error if the blog sotware is going to throw away some of my text! Apparently some subset of HTML markup is legal in these comments — who knew? No preview button either. Extra points to anyone who can figure out what I intended to write — I’m not going to fight with it.
September 17th, 2009 at 11:36 am
And now that Dan has manually fixed my first comment, my second comment makes no sense.