Compile time factorial

mrnutty 2 Tallied Votes 407 Views Share

This is a simple demonstration of meta programming. It shows the idea
of meta programming. It basically calculates the factorial of a number
before runtime. When I first saw the concept of meta programming,
it blew my mind so badly. I was so surprised that one could do this.
Its soooo kewl, don't you think?

avarionist commented: I'm still working out how exactly it works but man speed glorious speed +1
#include <iostream>

using std::cout;

template<int val>
struct staticFactorial{ 
	enum {result = val*staticFactorial<val-1>::result}; 
};
//template specilization
template<> struct staticFactorial<0>{ 
	enum {result = 1};
};

int main(){
	int A[] = {         staticFactorial<0>::result,
			    staticFactorial<1>::result,
			    staticFactorial<2>::result,
			    staticFactorial<3>::result,
			    staticFactorial<4>::result,
			    staticFactorial<5>::result,
			    staticFactorial<6>::result,
			    staticFactorial<7>::result
		     };

	for(int i = 0; i < sizeof(A)/sizeof(A[0]); ++i){
		cout << A[i] << "\n";
	}

}
avarionist 1 Junior Poster in Training

This is a simple demonstration of meta programming. It shows the idea
of meta programming. It basically calculates the factorial of a number
before runtime. When I first saw the concept of meta programming,
it blew my mind so badly. I was so surprised that one could do this.
Its soooo kewl, don't you think?

that was wicked fast nice bit :P

griswolf 304 Veteran Poster

Boost has a lot of nice meta programming code. I first saw this (or was it a Fibonacci?) quite a long time ago (probably about 15 years?).

You do have to be wary that too much of this kind of thing can make the compiler run a long time, use up space to store the precalculated values, and obfuscate your code, among other downsides. http://en.wikipedia.org/wiki/Template_metaprogramming#Benefits_and_drawbacks_of_template_metaprogramming

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.