Weblog entry — 2003-05-30 20:12:11

May 30, 2003

There's an excellent article about C++ templates over at kuro5hin.org, comparing them to SML, Lisp and Scheme and their very different, and in many ways superior and more elegant ways, of solving the same problems. Very constructive critique. I also learned something about templates, the only feature I haven't played around with in C++, I think.

Included in the article is this little gem, "ported" to more modern less C'ish C++:

#include <iostream>
#include <cstdlib>

template <int n>
class Fact {
    static const int val = Fact<n-1>::val * n; 

class Fact<0> {
    static const int val = 1;

int main(int argc, char *argv[])
  using namespace std;

  cout << "fact 4 = " << Fact<4>::val << "\n"; 
  cout << "fact 5 = " << Fact<5>::val << "\n"; 
  cout << "fact 6 = " << Fact<6>::val << "\n";
  cout << "fact 7 = " << Fact<7>::val << "\n";

  return EXIT_SUCCESS;

It compiles with "g++ -Wall -ansi -pedantic" on my OpenBSD machine, but do yourself the favour to compile it with "g++ -S" and read the resulting evil.s assembler file (I don't know assembler, but I did grasp this output). You'll see that the computations are carried out at compile time instead of at runtime, and this is so obviously a very speed enhancing technique to use.

But the Lisp/Scheme and SML solutions are so very sweet, I wish I had the time and energy to sit down and study those things.

Well, back to my regular schedule of C# and Perl, it just seems so plain in comparison.

Last edited: May 1, 2016