template bug?
Koroskin Denis
2korden+dmd at gmail.com
Fri Feb 29 01:58:26 PST 2008
On Fri, 29 Feb 2008 08:35:02 +0300, Denton Cockburn <diboss at hotmail.com>
wrote:
> In DMD 2.011
>
> import std.stdio;
>
> template factorial(real n)
> {
> static if (n == 1)
> const factorial = 1;
> else const factorial = n * factorial!(n - 1);
> }
>
> void main()
> {
> writefln(factorial!(5));
> }
>
> produces: -3.10504e+231
>
> when the template is changed to accept an int instead of a real, it
> produces the right output: 120
>
> What's the cause of this?
>
> Note: in 1.027, the version accepting a real still produces the correct
> output of 120.
Seems like a bug to mee, too. This produces incorrect output as well:
template factorial(real n) {
const real factorial = 1;
}
void main() {
writefln(factorial!(5));
}
In C++, one cannot use real as a template parameter. The following code
won't compile, although the code looks harmless :)
template<float t> class SomeClass {
static const float someValue = t;
}
void main() {
float value = SomeClass<5.0f>::someValue; // 5.0f expected
}
However this one can easily instanciate as much templates, at it wishes
because of rounding error on floating point arithmetics:
template<float t> float factorial() {
if (t == 1) { ///< this condition might never be satisfied
return 1;
} else {
return t*factorial(t-1);
}
}
int main() {
float t1 = factorial<5.0f>();
float t2 = factorial<5.1f>();
}
More information about the Digitalmars-d
mailing list