I am writing a very simple template class using Metaprogramming to compute sum in compile time, as below:
#include <iostream>
using namespace std;
template<int N>
class Sum
{
public:
enum {value = N + Sum<N-1>::value };
};
template<>
class Sum<0>
{
public:
enum {value = 0};
};
int main()
{
cout << Sum<501>::value << endl;
}
The interesting thing is:
- When I print Sum<500> and below, it works fine
When it comes to Sum<501>, the compile failed with:
sum.cpp:9: instantiated from
Sum<500>' sum.cpp:9: instantiated from
Sum<501>' sum.cpp:22: instantiated from heresum.cpp:9: error: incomplete type
Sum<1>' used in nested name specifier sum.cpp:9: error: enumerator value for
value' not integer constantSum<501> will report error of Sum<1>, Sum<502> will report error of Sum<2>, the difference is always 2, it seems to me the compiler has a limit resource of 500.
Any idea about this? and is their a way to break this limits?
Thanks.
Edit:
Thanks guys, the point is not about the algorithm, but rather the compiler limitation - I know there is an easy way to get sum:)
Edit2:
- Use gcc 4.6 +, the error message is much more helpful
sum.cpp:9:14: error: template instantiation depth exceeds maximum of 1024 (use -ftemplate-depth= to increase the maximum) instantiating ‘class Sum<1>’ sum.cpp:9:14: recursively instantiated from ‘Sum<1024>’ sum.cpp:9:14: instantiated from ‘Sum<1025>’ sum.cpp:22:22: instantiated from here
so yes, use ftemplate-depth is the right way. But how about in windows? the uplimits for VC9.0 is 499, and seems there is no option to set the template depth, see here
Sum<N>::value
byN * (N + 1) / 2
. – Glanti