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> ;)

Wednesday, February 8, 2012

"Undefined Reference" While Using Templates In C++

Did you get "collect2: ld returned 1 exit status" ??

If yes , then there is some linker's problem. Lets solve it.

I designed a template for one of my assignment , But I was unaware of "Declaring & Defining" fundamentals of templates in C++.

Here is some code :

//Add.h

#include "Basic.h"
using namespace std;
template <class T>
class Add{

        int x;
        int y;
        
public:
      Add(int x,int y);
      Dump();
};


Add.cpp

#include "Add.h"

template <class T>
Add<T>::Add(int x,int y):x(1),y(2){};


template <class T>
Add<T>::Dump(){
 cout<<x<<"  "<<y;
}

Output:
collect2: ld returned 1 exit status

Reason:
Templates are just a recipe , they are not code. In order to compile this code, it must be generated first, which needs to know templates definition & definition parameters which are passed to it. And compiler does not know about separate compilation (compiler doesn't know about anything about code outside of a file).

Solution:
Put the definitions in the header files itself :)


//Add.h

#include "Basic.h"
using namespace std;
template <class T>
class Add{

        int x;
        int y;
        
public:
      Add(int x,int y);
      Dump();
};

template <class T>
Add<T>::Add(int x,int y):x(1),y(2){};

template <class T>
Add<T>::Dump(){
 cout<<x<<"  "<<y;
}