January 17, 2004 DMD compiler does not like template recursion | ||||
---|---|---|---|---|
| ||||
I tried to calculate the factorial of an integer with templates, the D compiler did not like it. Is recursion not allowed in D templates? bye, roel // ------------------------------------------------------- // first attempt: with specialisation it would not compile template factor(int n) { int value() { if (n==0 || n==1) return 1; return n * factor!(n-1).value(); } } template factor(int n : 0) { int value() { return 1; } } template factor(int n : 1) { int value() { return 1; } } int main() { printf( "%d\n" , factor!(4).value() ); return 0; } // ------------------------------------------------------- // second attempt: testing for end condition // => going ballistic // => bug in compiler template factor(int n) { int value() { if (n==0 || n==1) return 1; return n * factor!(n-1).value(); } } int main() { printf( "%d\n" , factor!(4).value() ); return 0; } |
Copyright © 1999-2021 by the D Language Foundation