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 // corrected the little error :-) scusi template factor(int n) { int value() { 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; } |
January 17, 2004 Re: DMD compiler does not like template recursion | ||||
---|---|---|---|---|
| ||||
Posted in reply to Roel Mathys | Well the tradtional C++ way caused
dmd to blow up.
template factor(int n : 1)
{
enum { value = 1 }
}
template factor(int n)
{
enum { value = n*factor!(n-1).value }
}
int main(char[][] argv)
{
int i = factor!(3).value;
printf("%d\n",i);
return 0;
}
This method give the error:
examp.d(5): non-constant expression 3 * value
template factor(int n : 1)
{
const int value = 1;
}
template factor(int n)
{
const int value = n*factor!(n-1).value;
}
int main(char[][] argv)
{
int i = factor!(3).value;
printf("%d\n",i);
return 0;
}
Roel Mathys <roel.mathys@yucom.be> wrote in news:bubp7v$2h6n$1 @digitaldaemon.com:
> 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
> // corrected the little error :-) scusi
> template factor(int n)
> {
> int value()
> {
> 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