So, assume I have a template structure-function fib<i>::value
. I want to get nth fibonacci number in runtime. For this i create array fibs[] = { fib<0>::value, ... , fib<maxN>::value }
. Unfortunatelly, for some functions maxN
can be very large and I can't fill it with hands only. So I writed some preprocessor directives to make task easier.
#define fib(x) (fib<(x)>::value)
#define fibLine_level_0(x) fib(5*(x) + 0), fib(5*(x) + 1), fib(5*(x) + 2), fib(5*(x) + 3), fib(5*(x) + 4)
#define fibLine_level_1(x) fibLine_level_0(2*(x) + 0), fibLine_level_0(2*(x) + 1)
#define fibLine_level_2(x) fibLine_level_1(2*(x) + 0), fibLine_level_1(2*(x) + 1)
#define fibLine_level_3(x) fibLine_level_2(2*(x) + 0), fibLine_level_2(2*(x) + 1)
#define cAarrSize(x) (sizeof(x) / sizeof(x[0]))
And I use it so:
int fibs[] = { fibLine_level_3(0) };
for (int i = 0; i < cAarrSize(fibs); i++)
cout << "fib(" << i << ") = " << fibs[i] << endl;
The code that you may need:
template<int i>
struct fibPair{
static const int fst = fibPair<i-1>::snd;
static const int snd = fibPair<i-1>::fst + fibPair<i-1>::snd;
};
template<>
struct fibPair<0> {
static const int fst = 0;
static const int snd = 1;
};
template<int i>
struct fib {
static const int value = fibPair<i>::fst;
};
But this code is really ugly. What to do to make it more beautiful?
Constraints: this code must be used in sport programming. That means - no third-party libraries and sometimes no C++11 (but it can be)