D - DMD compiler does not like template recursion
- Roel Mathys (55/55) Jan 17 2004 I tried to calculate the factorial of an integer with templates,
- Patrick Down (38/102) Jan 17 2004 Well the tradtional C++ way caused
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;
}
Jan 17 2004
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;
}
Jan 17 2004








Patrick Down <pat codemoon.com>