
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Template Metaprogramming in C++
C++ Template metaprogramming (TMP)
Template metaprogramming (TMP) is a metaprogramming technique in which a template is used by the compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled.
The best use of template metaprogramming is in C++. The use of templates can be thought of as compile-time polymorphism.
The use of templates as a metaprogramming requires two distinct operations: A template must be defined and a defined template must be instantiated.
Syntax
The syntax of template metaprogramming is not defined by code, but we can explain it and create a syntax.
- Template Definition: We can define a template that act as a bluepring for the generating code.
- Template Specialization: We can create specialized version of a template for specific case.
- Recursion: Since template metaprogramming lacks mutable variables, recursion os often used for flow control.
template<return_type variable> struct fun_name { ... }; template<> struct fun_name<0> { ... };
Example of Template metaprogramming
The following example demonstrates template metaprogramming by calculating the factorial of a number at compile time using recursive template instantiation:
#include <iostream> // Primary template template < int N > struct Factorial { static constexpr int value = N * Factorial < N - 1 > ::value; }; // Base case specialization template < > struct Factorial < 0 > { static constexpr int value = 1; }; int main() { std::cout << "Factorial of 5: " << Factorial < 5 > ::value << std::endl; return 0; }
Factorial of a number:
Factorial of 5: 120
Example of Template Metaprogramming Compute 2 to the Power n
Here is another example of the template metaprogramming, which computes 2nd raise to the power of n. Where n is the positive integer:
#include <iostream> using namespace std; template < int n > struct computePower { enum { val = 2 * computePower < n - 1 > ::val }; }; template < > struct computePower < 0 > { enum { val = 1 }; }; int main() { cout << computePower < 4 > ::val << endl; return 0; }
Above code generates the following output ?
16