This is a quick post designed to show you how you can use templates for pre-calculations for optimisation or simply ease of use / design.
Let me give an example; imagine you have a class that has a buffer of size T, that stores information for use later, perhaps to return temporal statistics. The buffer size may rely on two parameters that define the size as X to the power of Y.
There doesn't exist a define to calculate powers at compile time, so normally you would have to have allocate the memory at run time. This can be useful but sometimes you want the memory to be allocated at compile time as it can make certain things easier and faster.
Firstly the power calculation isn't done at run time saving time there, it also means you know the exact size of the class before you create it, helping you keep tabs on your programs memory usage. It also means the memory is always there and you do not have to worry about checking pointer / memory validity. Now I know the time to calculate the power of a number is nominal however there will come a point where you need this solution. Trust me.
Right onto the code. You should have at least a basic understanding of templates to get the most out of this, so if you do not I suggest you look it up as there are lots of resources on Google.
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 };
};
And here is how you could use it within your class, 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 = MyPowT_Base, T_ Power>::result+1;
...
}

0 comments:
Post a Comment