Compiletime-Calculating Prime Numbers

rhphotography.net@googlemail.com wrote:
> OK so I came up with a very crude method of determining whether a
> number is a prime or not, but my compiler chokes when I attempt it for
> values greater than 500
>
> Here is the code
>
> template
> struct IsPrime
> {
> static const bool value = ((i%j)==0?(false):(IsPrime> j-1>::value));
> };
>
> template
> struct IsPrime
> {
> static const bool value = true;
> };
>
> int main()
> {
> IsPrime<100>::value; // fine
> IsPrime<1000>::value; // ---- Compiler (VStudion 2005) dies
> }
>
> So my question is ... should the compiler handle this?
Come on, how many resources do you think your compiler should be
required to have access to? Is a recursion depth of 999 reasonable?

> Is there a way to help the compiler out?
Yes, do not use naive prime number algorithms for this kind of work.
BTW, exactly why would you want to compute prime numbers at compile
time? Yes, the fact that we can do functional programming via template
metaprogramming is amazing but hardly what templates were designed for.

> Is there a more elegant solution?

Well if you insist you could always use a better algorithm but that
would require much more work at TMP. However I cannot imagine any place
where it would be useful.

--
Note that robinton.demon.co.uk addresses are no longer valid.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Google