m0nkeymafia

I came across this method when trying to figure out a way to have different sized buffers without having to allocate memory on the heap [using new].

I was making a class that could perform calculations on data over a time period, I wanted this class to be able to handle different times periods, and as such required different amounts of space.

I wanted my buffer to hold X^Y ints and C++ doesnt define a

mac

 ro for you to use, so it would normally have to be done run time, meaning all data would be allocated on the heap.

Using some template wizardy you can actually make a template calculating system to calculate powers, and other stuff, at compile time.

This first template class is the guts of the system, it defines the power template that will do the calculation. It works iteratively.

template <int base, int N>
class MyPow
{
public:
enum { result = base * MyPow<base, N-1> ::result };
};

//Next is the template specialisation for MyPow which defines result as 1 should the base reach 0.
template <int base>
class MyPow<base,0>
{
public:
enum { result = 1 };
};

//m_MaxDataPoints is defined as T_Base to the power of T_Power.
template <int T_Base, int T_Power> class MyClass
{
...
const int m_MaxDataPoints = MyPow<T_Base, T_Power> ::result+1;
...
}


Perkiset's Place Home   Politics @ Perkiset's