c++ function templates and memory hogging

Guido Loupias guidoloupias@gmail.com
Wed Dec 10 18:52:00 GMT 2008


Hi,

Why does the following behavior occur?

I have 2 naive implementations of fibonacci through function templates.
The first one has no problem compiling fib<46>(). However the second one starts 
eating significant memory when N > 23. It's gradual (seems to be exponential 
with regard to N) but when N = 27 the compilation process consumes about a gigabyte.

This happens when compiling with -O1 or higher.

(1)
template<int N>
inline int fib() {
     static const int n = fib<N-1>() + fib<N-2>();
     return n;
}
template<>
inline int fib<0>() {
     return 0;
}
template<>
inline int fib<1>() {
     return 1;
}

(2)
template<int N>
inline int fib() {
     return fib<N-1>() + fib<N-2>();
}
template<>
inline int fib<0>() {
     return 0;
}
template<>
inline int fib<1>() {
     return 1;
}

Regards,
Guido



More information about the Gcc-help mailing list