C++ and the compile time faculty
Freitag, 1. Januar 2010
I hate C++ fanboys. "Look C++ is the most p0werful and shiny language ev4r. You can't do that with any other language." followed by a copy of the faculty example from FQA or Wikipedia:
C++ dissolves the template to a simple multiplication (if -ftemplate-depth >= 4) and *woohoo replaces the multiplication with the result at compile time. There are many languages (and language features) out there with this capability, p.ex. Lisp Macros, Scheme, MetaOcaml or Template Haskell:
Fac.hs:
Main.hs:
120 at compile time:
#include <iostream>
using namespace std;
template<int n> struct fac {
static const int value = n*fac<n-1>::value;
};
template<> struct fac<1> {
static const int value = 1;
};
int main() {
cout << fac<5>::value << endl;
return 0;
}
using namespace std;
template<int n> struct fac {
static const int value = n*fac<n-1>::value;
};
template<> struct fac<1> {
static const int value = 1;
};
int main() {
cout << fac<5>::value << endl;
return 0;
}
C++ dissolves the template to a simple multiplication (if -ftemplate-depth >= 4) and *woohoo replaces the multiplication with the result at compile time. There are many languages (and language features) out there with this capability, p.ex. Lisp Macros, Scheme, MetaOcaml or Template Haskell:
Fac.hs:
Main.hs:
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Fac
import Language.Haskell.TH.Syntax
main = print $(lift $ fac (5 :: Int))
module Main where
import Fac
import Language.Haskell.TH.Syntax
main = print $(lift $ fac (5 :: Int))
120 at compile time:
>ghc -ddump-simpl Main.hs | grep print | grep 120
Main.main = print_rSB (GHC.Integer.smallInteger 120)
Main.main = print_rSB (GHC.Integer.smallInteger 120)
Trackbacks
Trackback-URL für diesen Eintrag
Keine Trackbacks
Kommentare