The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. January 08, 2009, 12:02:16 AM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: Compile time calculations  (Read 346 times)
m0nkeymafia
Expert
****
Offline Offline

Posts: 236


Check it!


View Profile
« on: May 28, 2007, 09:17:16 AM »

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 macro 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.
Code:
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;
...
}
Logged

I am Tyler Durden
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!