c++ function templates and memory hogging

Mojmir Svoboda mojmir.svoboda@illusionsoftworks.com
Wed Dec 10 19:27:00 GMT 2008


* Guido Loupias <guidoloupias@gmail.com> [2008-12-10 19:51:33 +0100]:

> 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.

i do not attempt to answer your problem, but i thought traditional way to do
compile-time computation was like:

template<int N>
struct fib {
    static int const n = fib<N-1>::n + fib<N-2>::n;
};
template<>
struct fib<0> {
    static int const n = 0;
};
template<>
struct fib<1> {
    static int const n = 1;
};

(or using enums) which behaves much better for me. local gurus will probably 
explain best why..

best regards,
mojmir



More information about the Gcc-help mailing list