Template Metaprogramming in C++

C++Server Side ProgrammingProgramming

When we write programs to do computation at compile time using a template, that is called Template Metaprogramming.

Example Code

#include <iostream>
using namespace std;

template<int n>struct power {
   enum { value = 4*power<n-1>::value };

template<>struct power<0> {
   enum { value = 1 };

int main() {
   cout <<”power is:”<< power<7>::value << endl;
   return 0;


power is:16384

In above example, When compiler sees power<7>::value, it tries to create an instance of power with parameter as 7, it turns out that power<6>must also be created as enumeration constant value must be evaluated at compile time. For power<6>, compiler need power<5>and so on. Finally, compiler uses funStruct<1>::value and compile time recursion terminates. This is called template metaprogramming.

Published on 03-Apr-2019 12:44:48