Pages

Friday, February 10, 2012

Calculating Value During Compile Time In C++

"If you think it's simple, then you have misunderstood the problem" - Bjarne Stroustrup

Recently one of my colleague asked me a question:

Print the value of (1 + 100 * 10 - 5 / 2 + 30) expression during compile time. And he allowed me to use any programming language.

For a while , I was not able to get the answer of this question. But after spending few minutes , I found out it's a good conceptual question.
The answer of this problem is simple, if you know about Templates in C++ a bit.

What are Templates?
Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.


The solution is based on Template Meta-Programming.
Template meta-programming is a technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. More on wiki.

#include <iostream>

using namespace std;
template<unsigned int n>
struct Expression {
   static const float result = n;
};

template<unsigned int exp>
struct _{ operator char() { return exp;} };

int main() {
        char(_<Expression<1 + 100 * 10 - 5 / 2 + 30>::result>());
        return 0;
}

If you want to explore more , try to print Factorial<n> ;)

No comments:

Post a Comment