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)


Project type:

C++ standard:


Libraries used:






Qt project file: CppTemplateMetaprogram.pro


CONFIG += console
CONFIG -= qt
QMAKE_CXXFLAGS += -Wall -Wextra -Weffc++ -Werror
SOURCES += 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()








  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