954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Compile time factorial

By D.Chhetri on Mar 29th, 2010 8:43 am

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?

#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";
	}

}
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

avarionist
Junior Poster in Training
70 posts since May 2010
Reputation Points: 11
Solved Threads: 3
 

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

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You