Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:
#include <iostream>
using namespace std;
template< int n >
struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };
template<>
struct factorial< 0 > { enum { ret = 1 }; };
int main() {
cout << "7! = " << factorial< 7 >::ret << endl; // 5040
return 0;
}
If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?
[Answering my own question]
The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from Generative Programming, Methods, Tools, and Applications by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of C++ Templates: The Complete Guide by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843.
Todd Veldhuizen has an excellent tutorial here.
A good resource for C++ programming in general is Modern C++ Design by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 "Compile-Time Assertions", 2.4 "Mapping Integral Constants to Types", 2.6 "Type Selection", 2.7 "Detecting Convertibility and Inheritance at Compile Time", 2.9 "NullType
and EmptyType
" and 2.10 "Type Traits".
The best intermediate/advanced resource I've found is C++ Template Metaprogramming by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256
If you'd prefer just one book, get C++ Templates: The Complete Guide since it is also the definitive reference for templates in general.