template bug?

Denton Cockburn diboss at hotmail.com
Fri Feb 29 07:15:18 PST 2008


On Fri, 29 Feb 2008 12:58:26 +0300, Koroskin Denis wrote:

> 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>();
> }

D template parameters can be:

    * types
    * integral values
    * floating point values
    * string literals
    * templates
    * or any symbol
http://www.digitalmars.com/d/2.0/templates-revisited.html

I guess this is a bug.  




More information about the Digitalmars-d mailing list