Steven T. Hatton wrote:
On Friday 04 July 2003 12:32 pm, Steven T. Hatton wrote:
I took the advice of others on this list and attempted to read Stroustrup's 'Phone Book'. I believe I've learned a lot thus far, but I'm still in the dark on many issues.
[snip]
Steven
Is this a problem for all attempts at recursive templates?
http://www.csci.csusb.edu/dick/examples/trex.cc
// template recursion // This is from the draft standard and soome articles in trade papers // However Gnu CC 2.7.0
template<int i> int fac() { return i>1 ? i*fac<i-1>() : 1; }
int fac<0>() { return 1; }
No. The code should work if you replace it with the following:
template<int i> int fac() {
return i > 1 ? i * fac<(i - 1) % 20>() : 1;
}
No need to define fac<0>.
The trick here is to use % to ensure that the only values of i that
fac<i> can be instantiated for are 0-19. Effectively you create a lookup
table for factorials. However, there is a catch: you can only use fac
with constants: i.e. the following won't even compile
for( int i = 0; i < 20; ++i ){
std::cout << fac<i>( x );
}
If that's the effect you want, create a real lookup table. The technique
might be more useful in something like:
template