Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) Template metaprogram

 

Technique to perform programs during compiling

 

There is no semantic difference between class and typename in a template-parameter [0] .

 

Example: calculate the factorial of an ( unsigned) integer during compile-time

 

 

#include <iostream>

 

template <unsigned int N>

struct Factorial

{

static unsigned int const value = N * Factorial<N-1>::value;

};

 

template <>

struct Factorial<0>

{

static unsigned int const value = 1;

};

 

int main()

{

std::cout

<< Factorial<0>::value << '\n'

<< Factorial<1>::value << '\n'

<< Factorial<2>::value << '\n'

<< Factorial<3>::value << '\n'

<< Factorial<4>::value << '\n'

<< Factorial<5>::value << '\n'

<< Factorial<6>::value << '\n'

<< Factorial<7>::value << '\n'

<< Factorial<8>::value << '\n'

<< Factorial<9>::value << '\n'

<< Factorial<10>::value << '\n'

<< Factorial<11>::value << '\n'

<< Factorial<12>::value << '\n';

}

 

 

Note that before the program starts to run, all factorials are already calculated.

 

References

  • C++. International Standard. ISO/IEC 14882. Second edition. Paragraph 14.1.2.

     

     

    Go back to Richel Bilderbeek's C++ page.

    Go back to Richel Bilderbeek's homepage.