Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Template metaprogram

 

Template metaprogramming is a technique to perform calculations during compiling only.

 

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

 

Below is an example to calculate the factorial of an ( unsigned) integer during compile-time. So when the program starts to run, all factorials are already calculated.

 

 

Other examples:

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppTemplateMetaprogram.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= qt
QMAKE_CXXFLAGS += -Wall -Wextra -Weffc++ -Werror
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

template <bool>
struct CtAssert;

template <>
struct CtAssert<true> {};

//The template metaprogram for factorial
template <unsigned int N>
struct factorial
{
  static unsigned const value = N * factorial<N-1>::value;
};

template <>
struct factorial<0>
{
  static unsigned const value = 1;
};

int main()
{
  CtAssert<(factorial<0>::value==1)>();
  CtAssert<(factorial<1>::value==1)>();
  CtAssert<(factorial<2>::value==2)>();
  CtAssert<(factorial<3>::value==6)>();
  CtAssert<(factorial<4>::value==24)>();
  CtAssert<(factorial<5>::value==120)>();
}

 

 

 

 

 

References

 

  1. 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.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml