Freigeben über


What I'm reading now: "C++ Template Metaprogramming"

I'm currently reading "C++ Template Metaprogramming". It's off to a great start.

The basic idea (so far) is that:

  1. You can write entire algorithms / programs in C++ templates, which are then executed as the compiler instantiates the template. 

  2. There is a discipline, structure, organization to these programs.

  3. The template programs are generally recursive and heavily use template specialization for the base case. 

Here's a simple example of writing Factorial like this.

 
// Simple demo of writing Factorial via a template
#include "stdafx.h"

// Recursive case: Factorial(N) = Factorial(N-1) * N
template <int N>
struct Factorial
{
public:
    static const int value = Factorial<N-1>::value * N;
};

// Use Template Specialization for base case: Factorial(1) = 1
template <>
struct Factorial<1>
{
    static const int value = 1;
};

void _tmain(int argc, _TCHAR* argv[])
{
    int v = Factorial<5>::value; 

    printf("%d\n", v); // prints 120
}

In this case, Factorial<5> is completely computed at compile time.  Code generated for Factorial<5> is:

 
    int v = Factorial<5>::value;
004113AE  mov         dword ptr [v],78h  // 78h = 120 = 5 factorial

    printf("%d\n", v); // prints 120

 

The Boost libraries heavily make use of these techniques. And it will certainly be helpful in fully appreciating what happens in STL.

Comments

  • Anonymous
    December 05, 2006
    obligatory snide lisp/scheme macro comment

  • Anonymous
    December 05, 2006
    I'm always so conflicted with templates. On one hand, you have STL. On the other hand, you have ATL...I guess it comes down to the fundamental truth: Just because you can do something doesn't mean that you should.

  • Anonymous
    December 05, 2006
    Another good book in the series is Andrei Alexandrescu's Modern C++ Design, which presents some of these template metaprogramming techniques and others along with design patterns (C++ and GoF). Some of his ideas were also incorporated into Boost, but the book's result is a library called Loki, which can be found here: http://loki-lib.sourceforge.net/

  • Anonymous
    December 13, 2006
    When people are asking for a debugger for language X, practically it means that the usage of language