genaray
genaray

Reputation: 1180

Factorial Meta Programming

We lately had a lesson about meta programming at our university... So i started to implement my own factorial meta code... this is the result.

template<int i>
struct fak{
    fak<i-1> next;
    int fakul = i * next.fakul;
};


template<>
struct fak<1>{
    int fakul = 1;
};

Meanwhile the variant from our script...

template<int i>
struct fakCool{

    static const int fak = i * fakCool<i-1>::fak;
};

template<>
struct fakCool<1>{

    static const int fak = 1;
};

My question after seeing the result from the script is... are both attempts meta programming ? And if so wheres the difference between them ? Whats the common way to implement a factorial meta ?

Upvotes: 0

Views: 57

Answers (1)

Jeevesh Juneja
Jeevesh Juneja

Reputation: 212

Second code :-

  • Doesn't need an object to be instantiated.

  • It does computation at compile-time.(due to static member in class)

First code, needs an object to be instantiated , and does computation at run-time.

Since , meta programming is about generating code using code, it is of no use to generate code after compilation has been done , as that code wouldn't be able to compile , even if it was generated. So, all meta programming happens during compile time only. And the first program isn't metaprogramming.

Upvotes: 3

Related Questions