
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++
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; }
Output
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.
Advertisements