(C++) Template metaprogram
January 9, 2018 · View on GitHub
(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
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
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
- C++. International Standard. ISO/IEC 14882. Second edition. Paragraph 14.1.2.