Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Factorial Template Example

Part of TemplatesCategory

Description

Demonstrates how a template function can be instantiated implicitly.

Related Example

Factorial by recursive template: FactorialRecursiveTemplateExample

Example

import std.stdio;

void main()
{
    for(int i=0; i<8; i++)
      writefln("%s! = %s", i, factorial(i));
}

template factorial(T)
{
   T factorial(T n)
   {
      if (n <= 1)
        return cast(T)1;
      else
        return cast(T)( n * factorial(n-1));
   }
}

Batch File

@echo off
set pgm=FactorialTemplateExample
dmd %pgm%.d
%pgm%.exe
pause
erase %pgm%.obj
erase %pgm%.map

Output

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040

Tested Compiler/Platform

Tested with Digital Mars D Compiler v0.176 on Windows 2000.

Souce

Based on digitalmars.D.bugs/7836 by Derek Parnell.