Code
#include <iostream> using namespace std; template<int n> struct Fibo { static int x; }; template<> int Fibo<0>::x = 1; template<> int Fibo<1>::x = 1; template<int n> int Fibo<n>::x = Fibo<n-1>::x + Fibo<n-2>::x; //marked line int main() { cout << Fibo<5>::x << endl; cout << Fibo<4>::x << endl; cout << Fibo<3>::x << endl; cout << Fibo<2>::x << endl; cout << Fibo<1>::x << endl; cout << Fibo<0>::x << endl; return 0; }
exits
0 0 1 2 1 1
in VC ++. (According to user M M., it compiles, as expected, in gcc). When the compiler hits the marked line with n=5 , it does not compile the same line again for n=4 , but simply processes Fibo<4>::x , as if it were declared using
template<> int Fibo<4>::x;
Why? Why it works, as expected when using
template<int n> struct Fibo { enum { x = Fibo<n-1>::x + Fibo<n-2>::x }; }; template<> struct Fibo<0> { enum { x = 1 }; }; template<> struct Fibo<1> { enum { x = 1 }; };
instead, but not with a static variable? And how do you fix the first code (without enum )?
source share