c++ function templates and memory hogging

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux